combining two python dictionaries into one when the net values are not positive

dictionary, python

Solution

How about something like:

dict((x, a.get(x, 0) + b.get(x, 0)) for x in set(a)|set(b))

example:

>>> a = {'a':1, 'b':2, 'c':-3, 'e':5, 'f': 5}
>>> b = {'b':3, 'c':4, 'd':5, 'e':-5, 'f': -6}
>>>
>>> dict((x, a.get(x, 0) + b.get(x, 0)) for x in set(a)|set(b))
{'e': 0, 'a': 1, 'f': -1, 'd': 5, 'c': 1, 'b': 5}

Problem

I have two python dictionaries that I'm trying to sum the values together on. The answer in: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? gets me most of the way. However I have cases where the net values may be zero or negative but I still want the values in the final dictionary. Even though Counters will accept negative values, it will only output a value if it's greater than zero. Example ``` from collections import Counter A = Counter({'a': 1, 'b': 2, 'c': -3, 'e': 5, 'f': 5}) B = Counter({'b': 3, 'c': 4, 'd': 5, 'e': -5, 'f': -6}) C = A + B print(C.items()) ``` Output: `[('a', 1), ('c', 1), ('b', 5), ('d', 5)]` `c = -3 + 4 = 1` is correct so the negative input is not an issue but e:0 and f:-1 are missing from the output How can I perform the summation and get all values output?

Original source

Related problems