Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 8 · Grouping with`defaultdict`

Grouping with defaultdict

Many tasks require grouping: by attributes, by categories, by clustering criteria. A normal dictionary needs checks to ensure the key exists before appending.

defaultdict (a specialized dictionary class) calls its factory when a missing key is accessed with square brackets, such as groups[3]. A membership test or .get() does not create a value.

Its signature is:

defaultdict(default_factory)

Where default_factory is a callable—often list,int, or set.

Example: grouping words by length:

from collections import defaultdict

words = ["cat", "apple", "dog", "pear", "bee"]
groups = defaultdict(list)

for w in words:
    groups[len(w)].append(w)

print(groups)
Listing 352 — Grouping with defaultdict

Output

defaultdict(<class 'list'>, {3: ['cat', 'dog', 'bee'], 5: ['apple'], 4: ['pear']})

This prints a dictionary-like structure where each key represents a word length and each value is the list of words of that length.

No checks required—defaultdict(list) ensures each new key starts with an empty list. This is heavily used in data preprocessing, graph adjacency lists, and clustering pipelines.