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
defaultdict(list)takes a function that makes the starting value. Here it islist, so a missing key starts as an empty list[].- The first time
by_genre["Fiction"]is used, the key is created with[], and then.append("Dune")adds to it. - With a normal dictionary,
by_genre[genre].append(title)would raise aKeyErrorfor the first book of each genre.
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").