defaultdict avoids repeated missing-key handling; setdefault is explicit but eager
defaultdict is a dict subclass that calls a factory function when a missing key is accessed. It is designed for grouping, counting, and building nested structures without KeyError checks. dict.setdefault(key, default) does similar work, but the default argument is evaluated every time, even when the key already exists. That makes setdefault wasteful for expensive defaults and awkward for nested structures.
defaultdict(list) is ideal for grouping; defaultdict(int) is ideal for counting.
setdefault is useful when you want explicit control and do not want missing-key access to silently create entries.
Trade-off: defaultdict can hide missing keys and mask bugs. In data validation code, explicit checks may be safer.
Common mistake: writing d.setdefault(key, expensive_call()) in a loop. expensive_call runs every iteration.
Version note: defaultdict has been in collections since Python 2.5; its behavior is stable.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience