1

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?

nad
  • 2,640
  • 11
  • 55
  • 96

1 Answers1

4

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]})
Ben
  • 5,952
  • 4
  • 33
  • 44