python - combine two dicts (adding values for keys that appear in both)

PHOTO EMBED

Mon Mar 15 2021 08:41:31 GMT+0000 (Coordinated Universal Time)

Saved by @zhwalker #python

>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)

{'a': 1, 'c': 7, 'b': 5, 'd': 5}
content_copyCOPY

https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe