Summing the contents of two collections.Counter() objects

PythonCounter

Python Problem Overview


I am working with collections.Counter() counters. I would like to combine two of them in a meaningful manner.

Suppose I have 2 counters, say,

Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})

and

Counter({'menu': 1, 'good': 1, 'bar': 3})

I am trying to end up with:

Counter({'menu': 21, 'good': 16, 'happy': 10,'bar': 8})

How can I do this?

Python Solutions


Solution 1 - Python

All you need to do is add them:

>>> from collections import Counter
>>> a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
>>> b = Counter({'menu': 1, 'good': 1, 'bar': 3})
>>> a + b
Counter({'menu': 21, 'good': 16, 'happy': 10, 'bar': 8})

From the docs:

>Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements.

Note that if you want to save memory by modifying the Counter in-place rather than creating a new one, you can do a.update(b) or b.update(a).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontumultous_roosterView Question on Stackoverflow
Solution 1 - PythonTerryAView Answer on Stackoverflow