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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

13 lines
Python 3.9+
from 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

stdout
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

  1. Use `groups.setdefault(initial, []).append(word)` with a regular dictionary
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.