The collections module provides specialized container types for tasks such as counting, grouping and representing named records.
Choose among Counter, defaultdict, namedtuple and ordered mappings by the behavior the task requires.
Counting and grouping both look like dictionary updates, but their missing-key
behaviour differs. Follow that difference through Counter and defaultdict,
then use named fields for records and explicit reordering for recent history.
Choose these containers for the operations they guarantee, not merely because
they shorten a loop.

Count votes in a poll
Four candidates, one vote per line. Counting by hand with a plain dict fails the moment a name shows up for the first time:
votes = ["A", "B", "A", "C", "A", "B"]
counts = {}
for v in votes:
counts[v] += 1
print(counts)Counter is a dict built for exactly this — every key starts at 0, so += 1 just
works, and it comes with .most_common() for free:
Counter is a dict (isinstance(tally, dict) is True), so every dict method
still works. .most_common() and the arithmetic (Counter(...) + Counter(...),
-, &, |) are what it adds.
Preparing this topic’s interactive investigation…
Roll call by class
A school's enrolment list pairs each student with their class. Grouping students by class is the same missing-key problem, one level up:
KeyErrorRun it and read which class crashes first. Then swap the plain dict for a defaultdict(list).
defaultdict(list) takes a factory — a function called with no arguments to
build the missing value. list makes [], int makes 0, and you can pass your
own function too. Once a roll is grouped, give each row real field names instead of
a bare tuple:
A missing-key lookup can change the mapping
Use the earlier dictionary model to distinguish lookup from insertion.
Counter reports a zero for a missing key without inserting it.
defaultdict calls its factory and inserts a value when d[key] misses.
Its .get() method does neither.
The first two membership checks are False; the indexed append creates
{'new': ['row-1']}. This matters in reports: merely inspecting
groups[unknown] can add an empty group. Use membership or .get() for a
non-inserting inspection. Pass the factory list, not the result list();
each missing key needs a separately created list, not a shared default.
Counter is also allowed to store zero and negative counts. subtract keeps
them, whereas multiset arithmetic such as a - b omits non-positive results.
For an inventory reconciliation, decide whether a deficit must remain visible
before choosing the operation.
Transfer this to a report of events per host: count events with Counter, keep
details with defaultdict(list), then query a host that never appeared. Predict
which operations alter the report's keys. Use namedtuple when field names
clarify a fixed record; like any tuple, it can still contain a mutable list.
Keep a recent-orders log in order
A kitchen screen shows orders in the sequence they arrived, and "bump" moves a
reopened order to the back of the queue. A plain dict already remembers
insertion order since Python 3.7 — but it has no way to change an item's
position without deleting and re-adding it. OrderedDict adds exactly that:
The one-word difference from a plain dict that trips people up is equality:
from collections import OrderedDict
a = OrderedDict([("x", 1), ("y", 2)])
b = OrderedDict([("y", 2), ("x", 1)])
print(a == b)Quick practice
from collections import Counter
bag = Counter("mississippi")
print(bag.most_common(1))Run it and see every total stuck at 0. Fix the line that's supposed to add up the prices.
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p[0] + p.y)🎯 Your turn
Write word_tally(words): count how many times each word appears, and return the
top 3 most common as a list of [word, count] pairs, most frequent first (ties
keep the order the words first appeared in).
word_tally(["a", "b", "a", "c", "b", "a"])→[["a", 3], ["b", 2], ["c", 1]]word_tally([])→[]
Hint: Counter(words).most_common(3) returns a list of (word, count) tuples —
turn each one into a list with [list(pair) for pair in ...].
Press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write most_frequent_char(s) returning the single most common character in s (ties go to whichever appeared first).
Write group_by_length(words) returning a dict mapping each length (as a string, e.g. "3") to the list of words with that length, in the order they appeared. Use defaultdict(list).
Define Point = namedtuple("Point", "x y"). Write closest_point(points): given a list of [x, y] pairs, build a Point for each and return the [x, y] of the one closest to the origin (0, 0) (ties go to whichever came first).
Write tag_report(items): items is a list of [tag, value] pairs. Return a dict mapping each tag to {"count": n, "total": sum}, in the order each tag first appeared.
Write recent_unique(ids, keep=3): replay ids one at a time into an OrderedDict. Seeing an id again moves it to the end (most recent); a new id is added at the end; once there are more than keep ids, drop the oldest one. Return the final ids, oldest to newest.