I learned about the collections.Counter() class recently and, as it’s a neat (and fast??) way to count stuff, I started using it.
But I detected a bug on my program recently due to the fact that when I try to update the count with a tuple, it actually treats it as a sequence and updates the count for each item in the tuple instead of counting how many times I inserted that particular tuple.
For example, if you run:
import collections
counter = collections.Counter()
counter.update(('user1', 'loggedin'))
counter.update(('user2', 'compiled'))
counter.update(('user1', 'compiled'))
print counter
You’ll get:
Counter({'compiled': 2, 'user1': 2, 'loggedin': 1, 'user2': 1})
as a result. Is there a way to count tuples with the Counter()? I could concatenate the strings but this is… ugly. Could I use named tuples? Implement my own very simple dictionary counter? Don’t know what’s best.
Sure: you simply have to add one level of indirection, namely pass
.updatea container with the tuple as an element.