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 \'comb
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 no c
in result after negating the c
's value in B
dictionary.
In [1]: from collections import Counter
In [2]: A = Counter({'a':1, 'b':2, 'c':3})
In [3]: B = Counter({'b':3, 'c':-4, 'd':5})
In [4]: A + B
Out[4]: Counter({'d': 5, 'b': 5, 'a': 1})
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:
- The Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.
- The
most_common()
method requires only that the values be orderable.- For in-place operations such as
c[key]
+= 1
, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true forupdate()
andsubtract()
which allow negative and zero values for both inputs and outputs.- The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
- The
elements()
method requires integer counts. It ignores zero and negative counts.
So for getting around that problem after summing your Counter you can use Counter.update
in order to get the desire output. It works like dict.update()
but adds counts instead of replacing them.
In [24]: A.update(B)
In [25]: A
Out[25]: Counter({'d': 5, 'b': 5, 'a': 1, 'c': -1})