Search code examples
pythoncounter

How to add or increment single item of the Python Counter class


A set uses .update to add multiple items, and .add to add a single one.

Why doesn't collections.Counter work the same way?

To increment a single Counter item using Counter.update, it seems like you have to add it to a list:

from collections import Counter

c = Counter()
for item in something:
    for property in properties_of_interest:
        if item.has_some_property: # simplified: more complex logic here
            c.update([item.property])
        elif item.has_some_other_property:
            c.update([item.other_property])
        # elif... etc

Can I get Counter to act like set (i.e. eliminate having to put the property in a list)?

Use case: Counter is very nice because of its defaultdict-like behavior of providing a default zero for missing keys when checking later:

>>> c = Counter()
>>> c['i']
0

I find myself doing this a lot as I'm working out the logic for various has_some_property checks (especially in a notebook). Because of the messiness of that, a list comprehension isn't always desirable etc.


Solution

  • Well, you don't really need to use methods of Counter in order to count, do you? There's a += operator for that, which also works in conjunction with Counter.

    c = Counter()
    for item in something:
        if item.has_some_property:
            c[item.property] += 1
        elif item.has_some_other_property:
            c[item.other_property] += 1
        elif item.has_some.third_property:
            c[item.third_property] += 1