Reputation: 35
This is the code:
def appd():
atho = []
data = {'snm':None}
for i in range(5):
data['snm'] = i
atho.append(data)
return atho
I expect that the result will be like this:
[{'snm': 0}, {'snm': 1}, {'snm': 2}, {'snm': 3}, {'snm': 4}]
but the result I got in python 3 platform is:
[{'snm': 4}, {'snm': 4}, {'snm': 4}, {'snm': 4}, {'snm': 4}]
How does that happen?
Upvotes: 2
Views: 160
Reputation: 26039
Dictionary cannot hold duplicate keys. If you try adding duplicates, the last added value is added to the key.
>>> d = {'a': 1}
>>> d['a'] = 2
>>> d['a'] = 3
>>> d
{'a': 3}
>>>
With data['snm'] = i
, you are basically doing the same thing and this dictionary is being added to list using append
.
To fix it, define data = {}
inside your loop, so every time you create a new dictionary before appending.
def appd():
atho = []
for i in range(5):
data = {}
data['snm'] = i
atho.append(data)
return atho
print(appd())
Upvotes: 1
Reputation: 1100
You are actually appending a reference to the original dictionary. The result you are seeing is the last iteration of your loop updating the dictionary, and thus all its references in your list.
Using atho.append(data.copy())
will work.
Upvotes: 1
Reputation: 411
Try this:
def appd():
atho = []
for i in range(5):
atho.append({'snm':i})
return atho
If you reuse the same oject, again and again, you are simply updating it's contents. The trick is either to explicitly copy the object or create a new one. You cannot simply keep overriting the same key and expect different values
Upvotes: 1
Reputation: 987
You are inserting the same dictionary again and again, instead of inserting a new dictionary whose key is snm.
On each iteration of the range, you are updating the value of the dictionary, therefore it gets updated for all the elements in the list, because all of them point to the same dictionary instance.
You must create a new dictionary on each iteration and then insert it.
Upvotes: 1
Reputation: 29081
A dictionary cannot have identical keys. So, every time you are doing data['snm'] = i
you are replacing the value. Also, your append
adds the same dictionary every time, not a copy. So, you list does not have 5 dictionaries, it has 5 references to the same dictionary. And, when it changes, all positions of your list change.
Short fix: add a new dict every time
for i in range(5):
atho.append({'snm': i})
Upvotes: 2