简体   繁体   中英

Python: How to create for loop that change dict value and append it to the list?

i tried to create a for loop that can change the value of dictionary 'title'. The new value will be then appended to the b list. So there will be 5 dict in b list with different 'title' value. This is my code.

dictionary = {'title': 'hello', 'black': 'white', 'yellow':'green'}
b = []
for a in range(5):
    dictionary['title'] = str(a)
    b.append(dictionary)
print b

The result is:

[{'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}]

[Finished in 0.136s]

Why all of the 'title' have the same value? How can I get a different number for each dicts appended to the list. Thanks

When you are appending dictionary , you are actually appending its reference since dictionaries are mutable - that's why all of the entries are actually pointing to a single copy of the dictionary. Use it's copy method to append a copy of it instead of the original:

b.append(dictionary.copy())

You keep appending the same dictionary (note that they don't all just have the same value, but the last value that element was set to); if you want them to be different, you have to make a new dictionary for each appending.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM