DefaultDict
Dictionaries with default values
Interview Relevant: Counting and grouping
DefaultDict
Dictionary that auto-creates missing keys.
Code Examples
Using defaultdict for convenience.
python
1from collections import defaultdict
2
3# Default value for missing keys
4d = defaultdict(int) # Default: 0
5d["a"] += 1 # No KeyError!
6
7# List as default (grouping)
8groups = defaultdict(list)
9for name, category in [("a", 1), ("b", 1), ("c", 2)]:
10 groups[category].append(name)
11# {1: ['a', 'b'], 2: ['c']}
12
13# Set as default
14seen = defaultdict(set)
15seen["user1"].add("page1")
16
17# Nested defaultdict
18tree = lambda: defaultdict(tree)
19t = tree()
20t["a"]["b"]["c"] = 1
21
22# Count characters
23text = "hello"
24counts = defaultdict(int)
25for c in text:
26 counts[c] += 1