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 lessonThis 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
- Count Character FrequencyBeginner
- Find the Top 2 Most Common WordsBeginner
- Group Names by First LetterIntermediate
- Predict the deque OutputBeginner
- Build a Recent History TrackerIntermediate
- Create and Use a namedtupleIntermediate
All Python exercises · 50 practice problems · Standard Library Essentials quiz