BeginnerCoder

Lesson 17 — defaultdict

Grouping made easy

A normal dict raises KeyError when you touch a missing key. defaultdict(list) creates an empty list automatically the first time a key is used, so you can append straight away. defaultdict(int) does the same with 0, which is handy for counting.

from collections import defaultdict
by_len = defaultdict(list)
by_len[3].append("cat")

Why it matters: grouping records by a field (city, date, category) is very common, and this removes the "is the key there yet?" checks.

Want it another way?
Task

Group the words by their first letter and print the result.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Python Intermediate

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.