I want to append a dict to a list, but the result I'm getting isn't what I want.
My code:
records=[]
record={}
for i in range(0,2):
record['a']=i
for j in range (0,2):
record['b']=j
records.append(record)
print records
I expected:
[{'a': 0, 'b': 0}, {'a': 0, 'b': 1}, {'a': 1, 'b': 0}, {'a': 1, 'b': 1}]
I get instead:
[{'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}]
Why is it only adding the last element every time?
You are reusing and adding one single dictionary. If you wanted separate dictionaries, either append a copy each time:
Or create a new dictionary each time:
The latter approach lends itself to translation to a list comprehension: