Count what matters.
Use dictionaries and Counter for grouping and lookup without repeated scans.
01 The idea
A hash map associates keys with values and supports expected constant-time access under normal assumptions. A frequency table uses each distinct observation as a key and stores how often it appears. collections.Counter expresses that pattern directly. Hashable keys must remain compatible with their hash and equality semantics while stored in a mapping.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from collections import Counter
states = ["open", "done", "open", "blocked", "done", "open"]
counts = Counter(states)
for state in sorted(counts):
print(state, counts[state])
print("missing:", counts["unknown"])blocked 1 done 2 open 3 missing: 0
03 Under the hood
- 1
Counter consumes the observations and accumulates counts. Sorting keys makes this report deterministic.
- 2
A missing Counter key reads as zero. Ordinary dictionaries instead raise KeyError when accessed with brackets and no such key exists.
- 3
Hash collisions can affect performance, and key equality affects grouping. Normalise text deliberately if "Open" and "open" should count as the same application state.
04 Your turn, builder
Count words case-insensitively and print the count for build.
Reveal one possible solution +
from collections import Counter
words = ["Build", "test", "BUILD"]
counts = Counter(word.casefold() for word in words)
print(counts["build"])05 Check your signal
What does a frequency table store?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.