You could use dict.viewitems with a for loop:
d1 = {'a': ('x', 'y'), 'b': ('k', 'l')}
d2 = {'a': ('m', 'n'), 'c': ('p', 'r')}
d3 = {}
for key, item in d1.viewitems() | d2.viewitems():
d3[key]= d3.get(key,()) + item
print(d3)
{'a': ('x', 'y', 'm', 'n'), 'c': ('p', 'r'), 'b': ('k', 'l')}
Or use a defaultdict:
from collections import defaultdict
d3 = defaultdict(tuple)
for key, item in d1.viewitems() | d2.viewitems():
d3[key] += item
print(d3)
Or use viewkeys for your lists as they are not hashable:
d1 = {'a': ['x', 'y'], 'b': ['k', 'l']}
d2 = {'a': ['m', 'n'], 'c': ['p', 'r']}
d3 = {}
for key in d1.viewkeys() | d2.viewkeys():
d3[key] = d1.get(key, []) + d2.get(key, [])
print(d3)
Which you can write as a dict comp:
d3 = {key:d1.get(key, []) + d2.get(key, []) for key in d1.viewkeys() | d2.viewkeys()}
for lists you could also chain the items:
d1 = {'a': ['x', 'y'], 'b': ['k', 'l']}
d2 = {'a': ['m', 'n'], 'c': ['p', 'r']}
from collections import defaultdict
d3 = defaultdict(list)
from itertools import chain
for key, v in chain.from_iterable((d1.items(),d2.items())):
d3[key] += v
print(d3)
defaultdict(<type 'list'>, {'a': ['x', 'y', 'm', 'n'], 'c': ['p', 'r'], 'b': ['k', 'l']})
For python3 just use .items
and .keys
as they return dictview objects.