defaultdict#

A dictionary that provides a default value for non-existent keys using a factory function.

Basic Usage#

from collections import defaultdict

# Default value is 0
d = defaultdict(int)
d["a"] += 1

print(d["a"]) # 1
print(d["b"]) # 0

Grouping items#

from collections import defaultdict

d = defaultdict(list)
d["fruit"].append("apple")

print(d["fruit"]) # ['apple']

Specific default value#

d = defaultdict(lambda: "N/A")
print(d["missing"]) # N/A

Removing Keys#

Use del or pop() just like a standard dictionary.

del d["key"]
val = d.pop("key", None)