defaultdict
A lot of interview problems have you group things under keys you haven’t seen yet. You might group words by their first letter or build a graph’s adjacency list. With a plain dict, the first time you use a new key, you have to check for it and create it yourself. defaultdict does that check for you. It lives in the collections module.
Here’s the syntax if that’s all you need:
from collections import defaultdict
groups = defaultdict(list) # missing keys start as []
groups["fruit"].append("apple")
counts = defaultdict(int) # missing keys start as 0
counts["apple"] += 1
seen = defaultdict(set) # missing keys start as set()
seen["fruit"].add("apple")
print(dict(groups), dict(counts), dict(seen))What defaultdict does
O(1)You give defaultdict a factory function. That’s a function with no arguments that makes a default value, like list or int. When you look up a key that isn’t there, defaultdict calls the factory. Then it stores the result under that key and returns it. Here’s how to group words by their first letter with defaultdict(list):
from collections import defaultdict
words = ["bat", "bar", "cat", "car", "dog"]
groups = defaultdict(list)
for word in words:
groups[word[0]].append(word)
print(groups)Notice there’s no if key not in groups check. The first time a letter shows up, list() runs and creates an empty list. Then .append() adds the word to it. It all happens in one line.
defaultdict vs dict.get() vs setdefault()
You can do the same grouping with a plain dict in two other ways. The first is to check for the key yourself and create the list the first time you see it:
words = ["bat", "bar", "cat", "car", "dog"]
groups = {}
for word in words:
key = word[0]
if key not in groups:
groups[key] = []
groups[key].append(word)
print(groups)The second is setdefault(). It does the same check and create as the if block above, but in one line:
words = ["bat", "bar", "cat", "car", "dog"]
groups = {}
for word in words:
groups.setdefault(word[0], []).append(word)
print(groups)Note
All three give the same result. defaultdict reads best when you add to the dict over and over in a loop. You don’t need any setup code with it. setdefault() is a good middle ground when you don’t want to import anything. Remember that it builds the default value (here, []) on every call, even when the key already exists. dict.get() is the right choice when you’re only reading a value with a fallback. It never adds anything to the dict.
The gotcha: reading a missing key inserts it
watch outA defaultdict treats reads and writes the same way. That means any lookup of a missing key creates it. This happens even when you’re just checking a condition:
from collections import defaultdict
counts = defaultdict(int)
print(len(counts))
if counts["missing"]:
print("truthy")
print(counts)
print(len(counts))Note
The if never printed "truthy" because 0 is falsy. But counts["missing"] still added "missing" to the dict with a value of 0. The dict went from empty to one entry just because you read from it. Use "missing" in counts instead to check whether a key exists without creating it.
Nested defaultdicts
A factory function can return another defaultdict. Then missing keys get created at every level. This is a quick way to build a weighted adjacency list:
from collections import defaultdict
graph = defaultdict(lambda: defaultdict(int))
graph["a"]["b"] += 1
graph["a"]["c"] += 1
graph["a"]["b"] += 1
print(dict(graph["a"]))
print(dict(graph["z"]))Note
graph["a"]["b"] += 1 works with no setup. The outer defaultdict creates an inner defaultdict(int) for "a". Then the inner one creates a 0 for "b" before adding 1 to it. The gotcha from above still applies at both levels. Printing graph["z"] created a new, empty entry for "z" in the outer dict just by asking for it.
Converting back to a plain dict
dict() copies what’s in a defaultdict into a regular dict. The regular dict won’t create missing keys on its own:
from collections import defaultdict
groups = defaultdict(list)
groups["a"].append(1)
groups["a"].append(2)
groups["b"].append(3)
print(groups)
print(dict(groups))Note
Here’s why you’d convert it before passing it to other code. Anyone holding the original can still create new keys just by reading. That’s the same gotcha from above. Once you convert it with dict(), looking up a missing key raises a normal KeyError, just like any other dict.
Where defaultdict shows up in interviews
You’ll use it most to build an adjacency list for a graph. With defaultdict(list), you can add an edge with graph[a].append(b). You don’t have to check whether a has shown up before.
- In Graph Breadth First Search and Graph Depth First Search, most solutions build an adjacency list this way before the traversal starts.
- Clone Graph uses a dictionary that maps each original node to its clone. That way, each node gets cloned exactly once, no matter how many edges point to it.
It’s useful outside of graphs too. Try defaultdict before you write your own if key not in d check any time a problem asks you to group things by some key. Grouping anagrams is a common example. You can also count things with defaultdict(int).