If itβs convenient to save all the values ββas a list (which I would prefer, it just adds extra headache and logic when your value data types are incompatible), you can use the approach below for your updated example using defaultdict
from itertools import chain from collections import defaultdict d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 2, 'b': 3, 'd': 4} d3 = defaultdict(list) for k, v in chain(d1.items(), d2.items()): d3[k].append(v) for k, v in d3.items(): print(k, v)
Print
a [1, 2] d [4] c [3] b [2, 3]
You also have the approach below, which I find slightly less readable:
d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 2, 'b': 3,} d3 = dict((k, [v] + ([d2[k]] if k in d2 else [])) for (k, v) in d1.items()) print(d3)
This will not change any of the source dictionaries and print:
{'b': [2, 3], 'c': [3], 'a': [1, 2]}
source share