73

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
tumultous_rooster
  • 12,150
  • 32
  • 92
  • 149
  • 1
    All you need to do is sum them. – Martijn Pieters Oct 14 '13 at 08:20
  • 12
    More specifically, `sum(counters, Counter())` to make sure the sum algorithm starts with a Counter base instead of a simple numeric base. – KobeJohn Sep 29 '16 at 04:34
  • @KobeJohn turn comment in answer? it's gold – Private Jul 12 '22 at 16:49
  • Thanks! The gods of python stackoverflow have deemed this question as a duplicate of the more generic dicts question and so I can't add an answer. The linked question does have at least one answer among many that includes the initial value feature of sum(). – KobeJohn Jul 14 '22 at 07:21

1 Answers1

133

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).

James Ko
  • 32,215
  • 30
  • 128
  • 239
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 1
    What if my values are 0? This operation seems skip them. I can only perform the addition if the values are at least 1. I am trying to prepare an always exact, default set of values for chart (0 is the amount that needs to be displayed). How would I force to merge two counters if one of them has zero values to persist those? – Hvitis Dec 20 '22 at 15:45