Skip to Content

When does collections outsmart a plain dict?

Category: Python Fundamentals

Answer

defaultdict gives a default for missing keys so you stop writing if k not in d: d[k] = []. Counter is a dict that counts hashable items and exposes .most_common(n). namedtuple is a tiny, immutable record. deque gives O(1) append/pop at both ends.

Concrete examples from the fca project context

Example 1

Counter(words).most_common(10) gives the most frequent words in a line.

Example 2

defaultdict(list) groups: for k, v in pairs: d[k].append(v) - no KeyError.

Example 3

deque for sliding window: d.append(x); if len(d) > K: d.popleft().

Example 4

namedtuple(“RGB”, “r g b”)(255,0,0) reads better than dict.

Data flow / flow chart

Counter for frequencies
  defaultdict for group-by
  deque for sliding window
  namedtuple for readable small records

Takeaway

Don’t reinvent counting, grouping, sliding windows, or named records. Use collections.