How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
Python code
13 linesfrom collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)
for initial, items in sorted(result.items()):
print(f"{initial}: {', '.join(items)}")
Output
A: apple, apricot
B: banana, blueberry
C: cherry
How it works
The defaultdict(list) factory automatically creates an empty list for any new key, so calling .append() on a missing key doesn't raise a KeyError. This makes grouping logic concise and readable. Converting to a regular dict at the end is optional but gives a cleaner representation for inspection. The for loop iterates over the grouped items in sorted key order to produce deterministic output. This pattern avoids manual if key not in groups: groups[key] = [] boilerplate.
Common mistakes
- Using a plain dict and forgetting to initialize lists, causing KeyError on first append
- Not converting defaultdict back to dict when you want normal missing-key behavior
- Assuming the group order is insertion order when printing without sorting
Variations
- Use `groups.setdefault(initial, []).append(word)` with a regular dictionary
- Use `itertools.groupby(sorted(words, key=str.upper))` or a comprehension with `sorted` for grouping
Real-world use cases
- Grouping user email addresses by domain for a bulk notification system.
- Indexing database records by a status field to build a dashboard summary.
- Batching log entries by error level for a monitoring pipeline.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.