For the needs of the project im iterating over some data and adding needed values to premade dictionary.
here is striped down example of code which represents my que
Because your dic
is created outside the loop, you only create one dict. If you want three different dicts, you need to create three different dicts, so move the initial creation of dic
inside the loop.
To answer your updated question, the issue is that although you think you are appending a new dict with each parsed.append(dic)
, you are just appending the same dict three times. Append
doesn't copy the dict. So whenever you modify that dict, all the dicts in parse
show the change, since they are all the same dict. This version of your second code example may be more illustrative:
>>> d = {'a': '', 'b': '', 'c': ''}
>>> stuff = []
>>> stuff.append(d)
>>> print stuff
[{'a': '', 'c': '', 'b': ''}]
>>> d['a'] = 'other'
>>> print stuff
[{'a': 'other', 'c': '', 'b': ''}]
>>> stuff.append(d)
>>> print stuff
[{'a': 'other', 'c': '', 'b': ''}, {'a': 'other', 'c': '', 'b': ''}]
>>> d['a'] = 'yet another'
>>> print stuff
[{'a': 'yet another', 'c': '', 'b': ''}, {'a': 'yet another', 'c': '', 'b': ''}]
Notice that changing the dict "works" in that it indeed changes the value, but regardless of that, the list still contains the same dict multiple times, so any changes you make overwrite whatever changes you made earlier. In the end, your list only contains the last version of the dict, because all earlier changes were overwritten in all dicts in the list.