Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 61 / 101

Count what matters.

Use dictionaries and Counter for grouping and lookup without repeated scans.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

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.

hash_maps.py
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"])
↳ EXPECTED OUTPUT
blocked 1
done 2
open 3
missing: 0

03 Under the hood

  1. 1

    Counter consumes the observations and accumulates counts. Sorting keys makes this report deterministic.

  2. 2

    A missing Counter key reads as zero. Ordinary dictionaries instead raise KeyError when accessed with brackets and no such key exists.

  3. 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

A SMALL MISSION

Count words case-insensitively and print the count for build.

Reveal one possible solution +
one_possible_solution.py
from collections import Counter
words = ["Build", "test", "BUILD"]
counts = Counter(word.casefold() for word in words)
print(counts["build"])

05 Check your signal

QUICK SIGNAL CHECK

What does a frequency table store?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.