Collections Module
Collections Module
Section titled βCollections ModuleβWhat it is
Section titled βWhat it isβcollections is a standard-library module of container types that solve common patterns the built-in list/dict/tuple donβt handle cleanly. The most-used one is defaultdict, a dict subclass that auto-creates a default value for missing keys instead of raising KeyError.
Before this feature
Section titled βBefore this featureβGrouping or counting with a plain dict means checking for the key every time:
words = ["cat", "dog", "cat", "bird", "dog", "cat"]
counts = {}for w in words: if w not in counts: counts[w] = 0 counts[w] += 1# or the slightly shorter counts[w] = counts.get(w, 0) + 1After this feature
Section titled βAfter this featureβfrom collections import defaultdict
words = ["cat", "dog", "cat", "bird", "dog", "cat"]
counts = defaultdict(int) # int() == 0, used for any missing keyfor w in words: counts[w] += 1 # no existence check needed
print(dict(counts)) # {'cat': 3, 'dog': 2, 'bird': 1}
groups = defaultdict(list)for w in words: groups[len(w)].append(w)print(dict(groups)) # {3: ['cat', 'dog', 'cat', 'dog', 'cat'], 4: ['bird']}Why this is better
Section titled βWhy this is betterβ- No existence checks: accessing a missing key runs the factory function (
int,list,set, or any zero-arg callable) instead of raisingKeyError. - Purpose-built alternatives exist for the common cases:
collections.Counterfor counting (with.most_common()built in),collections.dequefor a fast double-ended queue,collections.namedtuple/typing.NamedTuplefor lightweight immutable records. - Reads closer to intent:
counts[w] += 1says βincrement the count for w,β without aget/setdefaultdance in the way.
Key notes / edge cases
Section titled βKey notes / edge casesβ- The factory (
defaultdict(int)) is called with no arguments β it must be a zero-arg callable, not a value.defaultdict(0)fails;defaultdict(int)works becauseint()returns0. - Merely checking
if key in dddoes not create the key, but any subscript access (dd[key]) does β including insideprint(dd[key])for a key that doesnβt exist yet, which is a common surprise. Counteris arguably a better fit thandefaultdict(int)purely for counting β same underlying behavior, but with.most_common(n), arithmetic between counters, and a friendlier repr.
from collections import Counter
counts = Counter(words)print(counts.most_common(2)) # [('cat', 3), ('dog', 2)]Quick practice
Section titled βQuick practiceβ-
What does
defaultdict(list)[missing_key]do the first timemissing_keyis accessed?Answer
It calls `list()` to create an empty list, stores it under `missing_key`, and returns it β no `KeyError`. -
Why does
defaultdict(int)work for counting butdefaultdict(0)does not?Answer
The argument must be a zero-argument callable that produces the default value when invoked. `int` is callable (`int() == 0`); `0` is not callable at all. -
Whatβs a purpose-built alternative to
defaultdict(int)specifically for counting?Answer
`collections.Counter` β same auto-zero behavior, plus `.most_common()` and counter arithmetic.