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:
records = []
record = {}
for i in range(2):
record['a'] = i
for j in range(2):
record['b'] = j
records.append(record.copy())
Or create a new dictionary each time:
records = []
for i in range(2):
for j in range(2):
record = {'a': i, 'b': j}
records.append(record)
The latter approach lends itself to translation to a list comprehension:
records = [{'a': i, 'b': j} for i in range(2) for j in range(2)]