PythonMastery

Count anything with collections.Counter

Counter replaces the count-with-a-dict loop, answers most_common(n) directly, returns 0 for missing keys, and supports + and - between counts.

The count-with-a-dict loop is one of the first things everyone writes. The standard library already has it, with the useful questions built in.

Before

python
words = "the cat sat on the mat the end".split()

counts = {}
for w in words:
    if w in counts:
        counts[w] += 1
    else:
        counts[w] = 1

top = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:2]
print(top)
output
[('the', 3), ('cat', 1)]

After

python
from collections import Counter

words = "the cat sat on the mat the end".split()
counts = Counter(words)

print(counts.most_common(2))
print(counts["dog"])      # a missing key is 0, not a KeyError
output
[('the', 3), ('cat', 1)]
0

It does arithmetic too

Two counts can be added or subtracted, which turns "what changed?" into one line.

python
from collections import Counter

monday = Counter(apples=4, pears=2)
tuesday = Counter(apples=1, plums=5)

print(monday + tuesday)
print(monday - tuesday)   # only keeps what is still positive
output
Counter({'apples': 5, 'plums': 5, 'pears': 2})
Counter({'apples': 3, 'pears': 2})

When not to use it

For a single count of one thing, words.count("the") is shorter and says exactly that. And Counter counts hashable things: counting lists means turning each into a tuple first (why).

Learn it properly: collections: The Stdlib's Hidden Power, Dictionaries