Python Practice › Collections Programs › Program 5
Group words by first letter
Write a Python program to group words by their first letter with defaultdict.
Output
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Approach
defaultdict(list).
Solution
from collections import defaultdict words = ["apple", "avocado", "banana", "blueberry", "cherry"]groups = defaultdict(list)for w in words: groups[w[0]].append(w)print(dict(groups))Output
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Learn the concept
New to this topic? Read the lesson, then come back.