Skip to main content

← All terms · Standard library

collections.defaultdict

Dict that auto-creates missing keys with a factory: `defaultdict(list)` returns `[]` for any new key. Replaces `if k not in d: d[k] = []`-style code in counters and grouping.

counts = defaultdict(int)
counts[word] += 1

Learn this interactively:

Open lesson iv-43

Related — Standard library

pathlib.PathObject-oriented filesystem paths. `Path(".").rglob("*.py")` beats `os.walk + os.collections.CounterDict subclass that counts hashable items: `Counter("hello")` → `{'l': 2, ...}`.itertoolsIterator building blocks — `chain`, `groupby`, `combinations`, `accumulate`. Lazfunctools.cacheMemoize a pure function with `@functools.cache`. Replaces hand-rolled dict cachidataclasses.fieldConfigure a dataclass attribute — mutable defaults, init/repr behavior. Use `fie