nad
nad

Reputation: 2850

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?

Upvotes: 1

Views: 184

Answers (1)

Ben
Ben

Reputation: 6348

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]})

Upvotes: 4

Related Questions