Your currently iterating just the keys/values from dict1
, so the missing 10
key from dict2
will not be added.
Instead, you could merge both dictionaries with a collections.defaultdict
of lists, and add the items from both dictionaries as you iterate each one. To make this flexible for any number of dictionaries, we can use *args
to pass in variable length arguments.
We can also use a dictionary comprehension to convert the values to tuples at the end.
from collections import defaultdict
def mergeDicts(*dicts):
result = defaultdict(list)
for d in dicts:
for k, v in d.items():
result[k].append(v)
return result
merged = mergeDicts({1:3, 2:4}, {1:5, 2:6, 10:20})
print({k: tuple(v) for k, v in merged.items()})
Output:
{1: (3, 5), 2: (4, 6), 10: (20,)}