Appending a dictionary to a list in a a loop Python
You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:
yourlist.append(yourdict.copy())
I used yourdict
and yourlist
instead of dict
and list
; you don't want to mask the built-in types.
When you create the adict
dictionary outside of the loop, you are appending the same dict to your alist
list. It means that all the copies point to the same dictionary and you are getting the last value {1:99}
every time. Just create every dictionary inside the loop and now you have your 100 different dictionaries.
alist = []
for x in range(100):
adict = {1:x}
alist.append(adict)
print(alist)
Just put dict = {}
inside the loop.
>>> dict = {}
>>> list = []
>>> for x in range(0, 100):
dict[1] = x
list.append(dict)
dict = {}
>>> print list