Related: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
I\'d like to merge two string:string dictionaries, and concaten
One can use defaultdict to achieve this:
from collections import defaultdict
a = {'foo': 'bar', 'baz': 'bazbaz'}
b = {'foo': 'baz'}
new_dict = defaultdict(str)
for key, value in a.items():
new_dict[key] += value
for key, value in b.items():
new_dict[key] += value
print(new_dict)
# defaultdict(, {'foo': 'barbaz', 'baz': 'bazbaz'})
print(dict(new_dict))
# {'foo': 'barbaz', 'baz': 'bazbaz'}
If there are many dicts to join, we could use itertools.chain.from_iterable:
from collections import defaultdict
from itertools import chain
a = {'foo': 'bar', 'baz': 'bazbaz'}
b = {'foo': 'baz'}
c = {'baz': '123'}
dicts = [a, b, c]
new_dict = defaultdict(str)
for key, value in chain.from_iterable(map(dict.items, dicts)):
new_dict[key] += value
print(dict(new_dict))
# {'foo': 'barbaz', 'baz': 'bazbaz123'}