Part 04 / Topic 8 of 11
The collections toolbox: Counter, defaultdict and deque
The standard library's collections module (imports are covered in Part 7) ships three small upgrades to the core structures from this part. You will reach for them constantly in real code, and again in Stage 4's DSA part.
Real-world example: a canteen's end-of-day numbers — what sold most, who bought what, and the last few sales on the screen.
Counter: count things in one line
A Counter is a dict whose values are counts. Feed it any iterable; missing keys count as 0 instead of raising KeyError.
from collections import Counter
votes = ["chai", "coffee", "chai", "juice", "chai", "coffee"]
tally = Counter(votes)
print(tally) # Counter({'chai': 3, 'coffee': 2, 'juice': 1})
print(tally["chai"]) # 3
print(tally["lassi"]) # 0 (no KeyError for a missing key)
print(tally.most_common(2)) # [('chai', 3), ('coffee', 2)]
defaultdict: grouping without the "is the key there yet?" dance
Exercise 7 builds a nested dict with if name not in report: report[name] = {}. A defaultdict does that step for you: give it a factory (list, int, dict), and the first touch of a missing key creates the empty value.
from collections import defaultdict
orders = [("Asha", 250), ("Ravi", 120), ("Asha", 400)]
by_customer = defaultdict(list)
for name, amount in orders:
by_customer[name].append(amount) # no "if name not in ..." needed
print(dict(by_customer)) # {'Asha': [250, 400], 'Ravi': [120]}
deque: a list that is fast at BOTH ends
list.pop(0) has to shift every remaining item one place left, so it gets slower as the list grows. A deque ("double-ended queue") adds and removes at either end without any shifting — that is what makes it the right tool for queues (first in, first out). With maxlen= it also makes a neat "keep only the last N" history.
from collections import deque
recent = deque(maxlen=3) # keeps only the last 3
for page in ["home", "menu", "cart", "pay"]:
recent.append(page)
print(recent) # deque(['menu', 'cart', 'pay'], maxlen=3)
queue = deque(["t1", "t2", "t3"])
queue.append("t4") # join at the back
print(queue.popleft()) # t1 — served from the front
print(queue) # deque(['t2', 't3', 't4'])
| You need | Use |
|---|---|
| "How many of each?" | Counter |
| "Group these by key" | defaultdict(list) |
| A queue, or "last N items" | deque |
🔍 Going deeper: even reading a missing key on a
defaultdictcreates it — afterd["missing"],len(d)grows by one, which can surprise you in anifcheck; use"missing" in dto test without creating.collectionsalso hasnamedtuple, but Part 9's@dataclassis the modern way to make small record types. Queues anddequeget a full workout in Part 17 (DSA).
Read more: the official collections documentation.
Done here? The practice set for Part 4 — 8 exercises with solutions — is on the part page.