Content · Programming · Python

Python dict.setdefault() vs collections.defaultdict

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.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

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 defaultdict lookup with [] can create a new key as a side effect. Its get() 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 defaultdict lookup with [] can create a new key as a side effect.
Share this resourceSend this page to someone who may find it useful.