Python — Counting values with Counter
Python’s collections.Counter counts how often each hashable value appears. Use a label as a key to read its count.
A simple example
Look up one count
- Start with Key A has value 2
- Do this Look up A
- Result 2
counts = {"A": 2}
print(counts["A"])
2
Count labels without relying on storage order
Counter is a dictionary subclass specialized for counting hashable keys. The explicit list in the second loop defines the output order independently of how the counts are stored.
A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
from collections import Counter
counts = Counter(["red", "blue", "red"])
for color in ["red", "blue"]:
print(color, counts[color])
red 2 blue 1
The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.
Try it yourself
Insert another blue before the last red. What changes?
Check your answer
Both keys now have a count of two. The requested display order stays red, then blue.