A Pythonic Way to Combine Two Dicts
For example I have two dicts:
dict_a = {'a': 1, 'b': 2, 'c': 3} |
I need a pythonic way of 'combining' two dicts such that the result is:
{'a': 1, 'b': 5, 'c': 7, 'd': 5} |
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.
Use collections.Counter
:
from collections import Counter |
Counters are basically a subclass of dict, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.