PythonMastery

defaultdict in Python

Use collections.defaultdict to group items into lists or count them, without checking first whether each key exists.

A defaultdict is a dictionary that creates a starting value the first time you use a missing key. This removes the "is the key there yet?" check from grouping and counting code.

The program

python
from collections import defaultdict

books = [
    ("Fiction", "Dune"),
    ("Science", "Cosmos"),
    ("Fiction", "Emma"),
    ("History", "SPQR"),
    ("Science", "The Selfish Gene"),
]

by_genre = defaultdict(list)
for genre, title in books:
    by_genre[genre].append(title)

for genre, titles in by_genre.items():
    print(f"{genre}: {', '.join(titles)}")
output
Fiction: Dune, Emma
Science: Cosmos, The Selfish Gene
History: SPQR

How it works

Counting with defaultdict(int)

int() returns 0, so defaultdict(int) starts every count at 0:

python
from collections import defaultdict

votes = ["red", "blue", "red", "green", "red", "blue"]

tally = defaultdict(int)
for colour in votes:
    tally[colour] += 1

print(dict(tally))
print(tally["purple"])
print(dict(tally))
output
{'red': 3, 'blue': 2, 'green': 1}
0
{'red': 3, 'blue': 2, 'green': 1, 'purple': 0}

Notice the last line: just reading a missing key adds it. To check for a key without adding it, use "purple" in tally or tally.get("purple").

Learn the idea: collections: The Stdlib's Hidden Power, Dictionaries

A longer explanation: Group rows with defaultdict(list)