A gradebook groups students by class.
What You Need to Understand
dict.setdefault() inserts a default when a key is absent and returns the value; collections.defaultdict(factory) calls its factory automatically on missing-key indexing. Both can simplify grouping, but their behavior differs.
When to Use It
A gradebook groups students by class.
Step-by-Step Python Example
from collections import defaultdict
manual_groups = {}
manual_groups.setdefault("A", []).append("Maya")
auto_groups = defaultdict(list)
auto_groups["A"].append("Noa")
print(manual_groups)
print(dict(auto_groups))
How the Example Works
The setdefault() call explicitly supplies a new list. The defaultdict calls list() when indexing its missing key.
Example Output
{'A': ['Maya']}
{'A': ['Noa']}
{'A': ['Ann', 'Avi'], 'N': ['Noa']}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
from collections import defaultdict
groups = defaultdict(list)
for name in ["Ann", "Avi", "Noa"]:
groups[name[0]].append(name)
print(dict(groups))
Important Behavior and Edge Cases
A defaultdict lookup with [] can create a new key as a side effect. Its get() method does not trigger the factory.
Try It Yourself
Group three names by initial letter using a defaultdict.
Common Beginner Mistakes
- A
defaultdictlookup with[]can create a new key as a side effect. Itsget()method does not trigger the factory. - Applying the example without a clearly defined policy for missing keys, matching identifiers, or validating external values.
Key Takeaways
dict.setdefault()inserts a default when a key is absent and returns the value;collections.defaultdict(factory)calls its factory automatically on missing-key indexing.- The
setdefault()call explicitly supplies a new list. - A
defaultdictlookup with[]can create a new key as a side effect.