Hi, I want to merge two lists into one dictionary. Suppose I have two lists such as below
list_one = [\'a\', \'a\', \'c\', \'d\']
list_two = [1,2,3,4]
Since keys in dictionaries are unique, getting {'a': 1, 'a': 2, 'c': 3, 'd': 4} is impossible here for regular python dictionaries, since the key 'a' can only occur once. You can however have a key mapped to multiple values stored in a list, such as {'a': [1, 2], 'c': [3], 'd': [4]}.
One option is to create a defaultdict to do this easily for you:
from collections import defaultdict
list_one = ['a', 'a', 'c', 'd']
list_two = [1, 2, 3, 4]
d = defaultdict(list)
for key, value in zip(list_one, list_two):
d[key].append(value)
print(dict(d))
Which outputs:
{'a': [1, 2], 'c': [3], 'd': [4]}