Editor

Fix the defaultdict Bug

Advanced · Fix the bug · from Python collections: Counter, defaultdict, deque, and More

From the lesson: Python collections: Counter, defaultdict, deque, and More

Imagine you have a basic toolbox with a hammer and a screwdriver. They work fine for simple jobs. But when you're building a deck, you really want a power drill, a level, and a tape measure.

Read the lesson

This code tries to count word lengths using defaultdict, but it has a bug. The programmer used the wrong default factory. Fix it so that each word length maps to the count of words with that length.

Expected output: {5: 2, 6: 1, 3: 1}

from collections import defaultdict
words = ['hello', 'python', 'world', 'cat']
length_count = defaultdict(list) # Bug is here
for word in words:
length_count[len(word)] += 1
print(dict(length_count))

More collections exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz