Reputation: 9
Ok I have been working many times with list in python and it s the first time I encounter this problem : Near the strange place I've got this ( simplified )
list = []
dict = {}
things = {'1':'Am', '2':'I', '3':'Dumb?'}
[...]
for key,value in things.items():
if value:
dict[key]=value
print(dict)
list.append(dict)
print(list)
And get the this result :
{'1':'Am'}
[{'1':'Am'}]
{'2':'I'}
[{'2':'I'},{'2':'I'}]
{'3':'Dumb?'}
[{'3':'Dumb?'},{'3':'Dumb?'},{'3':'Dumb?'}]
hinhin, someone have ever get this ? I, m stuck, thank iou :)
Upvotes: 0
Views: 57
Reputation: 476659
This is not a bug. You simply add the same dictionary multiple times to the list. As a result if you manipulate that dictionary, you see the changes in all elements of the list, since these all refer to the same dictionary.
You should create a new dictionary each iteration, for example with:
result = []
things = {'1':'Am', '2':'I', '3':'Dumb?'}
for key, value in things.items():
if value:
result.append({key: value})
print(list)
Or with simple list comprehension:
result = [{k: v} for k, v in things.items() if v]
Upvotes: 1