Reputation: 133
I am trying to make a list of dictionaries in python. Why don't these three methods produce the same results?
A = [{}]*2
A[0]['first_name'] = 'Tom'
A[1]['first_name'] = 'Nancy'
print A
B = [{},{}]
B[0]['first_name'] = 'Tom'
B[1]['first_name'] = 'Nancy'
print B
C = [None]*2
C[0] = {}
C[1] = {}
C[0]['first_name'] = 'Tom'
C[1]['first_name'] = 'Nancy'
print C
this is what I get:
[{'first_name': 'Nancy'}, {'first_name': 'Nancy'}]
[{'first_name': 'Tom'}, {'first_name': 'Nancy'}]
[{'first_name': 'Tom'}, {'first_name': 'Nancy'}]
Upvotes: 0
Views: 84
Reputation:
Barmar has a very good answer why. I say you how to do it well :)
If you want to generate a list of empty dicts use a generator like this:
A = [{}for n in range(2)]
A[0]['first_name'] = 'Tom'
A[1]['first_name'] = 'Nancy'
print (A)
Upvotes: 0
Reputation: 780852
Your first method is only creating one dictionary. It's equivalent to:
templist = [{}]
A = templist + templist
This extends the list, but doesn't make a copy of the dictionary that's in it. It's also equivalent to:
tempdict = {}
A = []
A.append(tempdict)
A.append(tempdict)
All the list elements are references to the same tempdict
object.
Upvotes: 3