Merge two dicts by same key
if not all the keys from d2
are in d1
, then the simplest thing is using set union and dict.get
:
combined_keys = d1.keys() | d2.keys()
d_comb = {key: d1.get(key, []) + d2.get(key, []) for key in combined_keys}
You almost had it, instead use +
to append both lists:
{key: d1[key] + d2[key] for key in d1}
{'a': [2, 4, 5, 6, 8, 10, 12, 15],
'b': [1, 2, 5, 6, 9, 12, 14, 16],
'c': [0, 4, 5, 8, 10, 21, 23, 35]}