Group Names by First Letter
Intermediate · Write the code · 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 lessonUse defaultdict(list) to group the names ['Alice', 'Bob', 'Anna', 'Charlie', 'Ben'] by their first letter. Print the resulting dictionary (convert to a regular dict first with dict()).
from collections import defaultdict
names = ['Alice', 'Bob', 'Anna', 'Charlie', 'Ben']
# Group names by first letter using defaultdict
More collections exercises
- Count Character FrequencyBeginner
- Find the Top 2 Most Common WordsBeginner
- Predict the deque OutputBeginner
- Build a Recent History TrackerIntermediate
- Create and Use a namedtupleIntermediate
- Fix the defaultdict BugAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz