Appending a dictionary to a list in a a loop Python

Acoop picture Acoop · May 18, 2014 · Viewed 62.2k times · Source

I am a basic python programmer so hopefully the answer to my question will be easy. I am trying to take a dictionary and append it to a list. The dictionary then changes values and then is appended again in a loop. It seems that every time I do this, all the dictionaries in the list change their values to match the one that was just appended. For example:

>>> dict = {}
>>> list = []
>>> for x in range(0,100):
...     dict[1] = x
...     list.append(dict)
... 
>>> print list

I would assume the result would be [{1:1}, {1:2}, {1:3}... {1:98}, {1:99}] but instead I got:

[{1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}]

Any help is greatly appreciated.

Answer

Martijn Pieters picture Martijn Pieters · May 18, 2014

You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:

yourlist.append(yourdict.copy())

I used yourdict and yourlist instead of dict and list; you don't want to mask the built-in types.