JL Peyret JL Peyret - 1 year ago 81
Python Question

collections.Counter - can I add/increment individual elements to a Counter?

Can I add/increment individual elements to a Counter?

I am getting each element one by one from an xml parse stream, so my Counter use here is always going to be based on 1-by-1.

OK, I know I can do this:

from collections import Counter
counter = Counter("abaa")

print ("counter:", counter) #('counter:', Counter({'a': 3, 'b': 1}))

#and I can do this as well...
def track_data(counter, data):

#let's say I am in a function that receives data one by one.
one_element_of_incoming_data = "a"
track_data(counter, one_element_of_incoming_data)
print ("counter:", counter) #('counter:', Counter({'a': 4, 'b': 1}))

but what I really want to do is to increment without building a new counter:


and see my count for 'a' go up by one. It doesn't look like it's in the Counter API, am I missing something?

Yes, I know that I could use a defaultdict and increment myself, but I was kinda expecting this capability out of a Counter.

Answer Source


from collections import Counter

counter = Counter()
for s in 'abcdefga':
    counter[s] += 1

In this way, Counter works like a defaultdict(int). However, it also has some handy methods since it is made to work with counts of things (e.g. you can add two Counters together, it has a more convenient constructor, etc.).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download