Mastery
Mastery/Python/J. Stdlib gems
T1 · high-leverage

collections: Counter, defaultdict, deque, ChainMap

Four stdlib types that replace a surprising amount of hand-rolled boilerplate: Counter for frequency counting, defaultdict for "group into a dict without checking if the key exists yet," deque for a double-ended queue with O(1) operations at both ends (vs. a list's O(n) insert(0, ...)), and ChainMap for layering multiple dicts into one logical view without copying them.

python
from collections import Counter, defaultdict, deque, ChainMap

words = "the quick brown fox jumps over the lazy dog the fox runs".split()

c = Counter(words)
print("Counter:", c)
print("most_common(2):", c.most_common(2))

dd = defaultdict(list)
for word in words:
    dd[len(word)].append(word)
print("defaultdict grouped by length:", dict(dd))

d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print("deque after appendleft/append:", d)

cm = ChainMap({"a": 1}, {"b": 2, "a": 99})
print("ChainMap lookup (first dict wins):", cm["a"], cm["b"])

The O(1) vs O(n) claim only shows up at real scale -- on a large structure, deque wins by three orders of magnitude:

python
import timeit

setup_list = "lst = list(range(200000))"
setup_deque = "from collections import deque; d = deque(range(200000))"

t_list = timeit.timeit("lst.insert(0, -1); lst.pop(0)", setup=setup_list, number=2000)
t_deque = timeit.timeit("d.appendleft(-1); d.popleft()", setup=setup_deque, number=2000)

print(f"200,000-element structure, 2000 operations each:")
print(f"  list.insert(0,...) + pop(0): {t_list:.4f}s")
print(f"  deque.appendleft + popleft:  {t_deque:.4f}s")
print(f"  list is ~{t_list/t_deque:.0f}x slower -- insert(0) must shift every remaining element")

Interview angle

A practical, low-drama fluency check: does the candidate reach for collections.Counter/defaultdict or hand-roll the equivalent with a plain dict and manual if key not in d checks? It's not a hard question, but hand-rolling stdlib-provided functionality is a mild but real signal about how much Python someone's actually written versus translated from another language.

In the industry

Counter and defaultdict show up constantly in real data-processing and analytics code — frequency counts, grouping, and histogram-building are extremely common tasks these two types were built for. deque is the correct choice any time code needs a sliding window, a work queue, or repeated insertion/removal from both ends — using a plain list for that pattern is a recurring, easy-to-miss performance bug, since the O(n) cost of list.insert(0, ...) only becomes visible at scale, exactly as the benchmark here shows.