Group words by first letter

EasyCollections Programs · 5 of 20

Write a Python program to group words by their first letter with defaultdict.

Advertisement
Output
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

Approach

  1. defaultdict(list).

Solution

Python
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.

More collections programs

← All 20 Collections Programs

Leave a Comment