Counting with Counter

collections · Essentials · 8 min

Counting words, events, errors or votes is one of the most common data tasks.

A Counter is a dict subclass that maps items to counts. Build one from any iterable of hashable items:

from collections import Counter
words = Counter(text.split())

It behaves like a dict, with conveniences:

  • Missing items count as 0 instead of raising KeyError: words["zebra"] is 0. Reading doesn't insert the key.
  • c.most_common(3) returns the three highest (item, count) pairs, sorted by count; ties keep first-seen order. Without an argument it returns all items.
  • c.update(iterable) adds more counts; c[item] += 1 works directly too.
  • c.total() (3.10+) sums all counts.

You can also build a Counter from a mapping or keyword arguments: Counter({"a": 2}), Counter(a=2, b=1).

Counting a string counts its characters, a common surprise: Counter("hello") has l: 2. Split first if you want words.

A Counter replaces the classic pattern of if key not in d: d[key] = 0 followed by d[key] += 1, and it's implemented with a C helper, so counting a large iterable is fast.

Example

from collections import Counter

text = "the cat and the hat and the bat"
words = Counter(text.split())
print(words["the"], words["dog"])   # 3 0
print(words.most_common(2))         # [('the', 3), ('and', 2)]
print(words.total())                # 8

words.update(["cat", "cat"])
words["hat"] += 1
print(words["cat"], words["hat"])   # 3 2

print(Counter("hello"))             # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
status = Counter(code for code in [200, 404, 200, 500, 200])
print(status.most_common(1)[0])     # (200, 3)

Remember

  • Counter(iterable) tallies items; missing keys count as 0
  • most_common(n) returns the top items with counts
  • Counting a string counts characters, not words

Watch out for

  • Passing a sentence string directly to Counter when you meant to count words.

Check yourself

  1. c = Counter(['a', 'b', 'a']). What does c['z'] return, and does 'z' get added?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/collections.html#collections.Counter