Python: appending to list of dicts

4.4k views Asked by At

When I generate a dict, and add it to a list, then generate a second dict with similar structure and append it to that list, the resulting list is two copies of the second dict, as opposed to a list containing both the first and second dicts.

My code:

    i=1
    UnitTabs = {};   TextUnits=[]
    theseTextUnits = {}
    theseTextUnits['documentId'] = i
    theseTextUnits['xPosition'] = 200; theseTextUnits['yPosition'] = 200;  theseTextUnits['name'] = 'From date'
    TextUnits.append(theseTextUnits)
    theseTextUnits['xPosition'] = 250; theseTextUnits['yPosition'] = 250;   theseTextUnits['name'] = 'To date'
    TextUnits.append(theseTextUnits)
    print(TextUnits)

Expected output:

[{'xPosition': 200, 'yPosition': 200, 'name': 'From date', 'documentId': 1},
 {'xPosition': 250, 'yPosition': 250, 'name': 'To date', 'documentId': 1}]

Actual output:

[{'xPosition': 250, 'yPosition': 250, 'name': 'To date', 'documentId': 1}, 
 {'xPosition': 250, 'yPosition': 250, 'name': 'To date', 'documentId': 1}]
3

There are 3 answers

0
AKS On BEST ANSWER

It is happening because you are modifying the same dict instance:

theseTextUnits['name'] = 'To date'

And, this will change the value in the original dict as well. What you need to do is copy the dict and then modify the values you want to.

import copy
newDict = copy.deepcopy(theseTextUnits)
newDict['xPosition'] = 250
newDict['yPosition'] = 250
newDict['name'] = 'To date'
TextUnits.append(newDict)
0
usernamenotfound On

What's happening here is that you are editing the same dictionary. Python never implicitly copies objects. If you use the copy method it will fix the issue

TextUnits.append(theseTextUnits.copy())

0
Stephen C On

Dictionaries in Python are mutable objects. This means that the actual value can be changed (as opposed to returning a new object)

For instance:

a={1:1}
b=a
b[1]=2
print(a)

{1:2}