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}]
It is happening because you are modifying the same dict instance:
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.