14

I am using a Counter like this:

from collections import Counter

totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)

totals += c_one
totals += c_two    

# Output: Counter({'a': 20})
print(totals)

Which is not at all what I expected. I expected to see:

Counter({'a': 20, 'b': -100})

Where did my negatives go, and is there some Counter that will let me use negatives?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290

1 Answers1

15

From the docs:

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.

(emphasis added)

However, if you look a little closer you'll find your answer:

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.

(emphasis added)

All you have to do is make one tiny change, and your example will work:

from collections import Counter

totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)

# Instead of totals += c_one; totals += c_two
totals.update(c_one)
totals.update(c_two)    

# Output: Counter({'a': 20, 'b': -100})
print(totals)
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290