简体   繁体   中英

Python: updating a list as a dictionary value

I want to have lists as values of a dictionary and want to ability to append to those list when there is a match in key.

I understand I can do it when the list is predefined as follows:

hashmap = {}
k = [1,2,3]
val = ['a','b','c']
for i in k:
    hashmap[i]= val
for j in hashmap.keys():
    print(hashmap[j])

But what if the contents of the val list is not defined. How do I declare it runtime and append to those list?

Use a defaultdict to create the list if it doesn't exist:

from collections import defaultdict

dd = defaultdict(list)
dd['a'].append(1)  # create the list if it doesn't exist
print(dd)
# defaultdict(<class 'list'>, {'a': [1]})

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