For example I have two dicts:
Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}
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.
A more generic solution, which works for non-numeric values as well:
or even more generic:
For example:
This solution is easy to use, it is used as a normal dictionary, but you can use the sum function.
The best to use is dict():
Definitely summing the
Counter()
s is the most pythonic way to go in such cases but only if it results in a positive value. Here is an example and as you can see there is noc
in result after negating thec
's value inB
dictionary.That's because
Counter
s were primarily designed to work with positive integers to represent running counts (negative count is meaningless). But to help with those use cases,python documents the minimum range and type restrictions as follows:So for getting around that problem after summing your Counter you can use
Counter.update
in order to get the desire output. It works likedict.update()
but adds counts instead of replacing them.You could easily generalize this:
Then it can take any number of dicts.
From python 3.5: merging and summing
Thanks to @tokeinizer_fsj that told me in a comment that I didn't get completely the meaning of the question (I thought that add meant just adding keys that eventually where different in the two dictinaries and, instead, i meant that the common key values should be summed). So I added that loop before the merging, so that the second dictionary contains the sum of the common keys. The last dictionary will be the one whose values will last in the new dictionary that is the result of the merging of the two, so I thing the problem is solved. The solution is valid from python 3.5 and following versions.
Reusable code