简体   繁体   中英

how do you append a list to a dictionary value in Python?

So if you have some dictionary like this

dictionary={}
dictionary['a']=1
dictionary['a']=2
print(dictionary)

this would print {'a':2} and replaces the 1 Is there any way I can add 2 to the key 'a' as a list? I know i can do something this like:

dictionary['a']=[1,2]

but I don't want to do it like this. Essentially what i am asking is how can i add the new value to my key using a list instead of replacing the previous value. Appreciate the help!

dictionary = {}
dictionary['a'] = []
dictionary['a'].append(1)
dictionary['a'].append(2)
print(dictionary)

It would be worth considering using a defaultdict if every value in the dict is/will be a list :

from collections import defaultdict

d = defaultdict(list)

d['a'].append(1)
d['a'].append(2)

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