CodeBlanks Logo Icon CodeBlanks

defaultdict

Learn default-value dicts with defaultdict.

defaultdict

defaultdict produces a default value instead of raising KeyError when you access a missing key. A factory function is given to the constructor; types like int, list, dict can be used.

Example: d = defaultdict(int). Writing d["a"] += 1 first creates d["a"] as 0, then it becomes 1. So for counting or grouping tasks you do not need to check whether the key exists first.

Which factory gives what?

defaultdict(int) defaults to 0; ideal for counting. defaultdict(list) produces an empty list; ideal for grouping. defaultdict(dict) gives an empty dict; useful for nested structures.

Grouping example: groups = defaultdict(list)\nfor word in words:\n groups[len(word)].append(word). This code collects words of the same length into a list. Each length triggers an automatic empty list when first seen; no if len(word) in groups check is needed.

Practice Count with defaultdict

Start with from collections import defaultdict. Create a defaultdict with d = defaultdict(int). Call d["a"] += 1 twice. Then print the count of a with print(d["a"]).

Starter code

main.py
# Count with defaultdict(int)

Sample solution

main.py
# Count with defaultdict(int)
from collections import defaultdict

d = defaultdict(int)
d["a"] += 1
d["a"] += 1
print(d["a"])

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 defaultdict factory argument

Question
from collections import defaultdict

d = defaultdict(____)
d["a"] += 1
print(d["a"])
Answer
from collections import defaultdict

d = defaultdict(int)
d["a"] += 1
print(d["a"])

Explanation: The int factory produces 0 as default.

2 What does defaultdict(int) return for a missing key?

  • KeyError
  • None
  • 0 Correct answer
  • Empty string

Explanation: defaultdict(int) produces 0 for missing keys.

3 Match factory and default

Term Meaning
int 0
list []
dict {}
str ""

All lessons in Intermediate