I had this:
[{'name': 'Peter'}, {'name': 'Anna'}]
And I wanted to make this out of it:
[{'name': 'Peter Williams'}, {'name': 'Anna Williams'}]
So I did:
>>> li = [{'name': 'Peter'}, {'name': 'Anna'}]
>>> new_li = []
>>> dic = {}
>>> for i in li:
... dic["name"] = i["name"] + " Williams"
... new_li.append(dic)
But:
>>> new_li
[{'name': 'Anna Williams'}, {'name': 'Anna Williams'}]
Why?
Could you also show how to best get [{'name': 'Peter Williams'}, {'name': 'Anna Williams'}]?
Edit
The reason why I didn’t understand this behavior is because I assumed that:
>>> dict = {'name':'Peter'}
>>> lis = [dict]
>>> dict['name'] = 'Olaf'
Where
>>> print lis
gives
[{'name': 'Peter'}]
While it actually is
[{'name': 'Olaf'}]
Because you’re using the same dictionary object in each iteration.
On the second iteration, you are altering the value that you assigned to the
namekey in the previous iteration, and your list ends up containing two references to the same object.I’d strongly recommend checking out the “Python Tutor” tool (pythontutor.com), which allows you to visualise the execution of some python code, and see what objects are being created in the stack. e.g. Python Tutor with your code
The correct way to do what you wanted would be:
This way a new dictionary object is created with each iteration.
A more concise solution: