Group Words by First Letter

Medium ⏱ 12 min 52% acceptance ★★★★★ 4.9
Write a function group_by_first_letter(words) that returns a dict mapping each first letter (lowercase) to a list of the words that start with it, preserving the order words first appear in words.

Examples

Example 1
Input
group_by_first_letter(['apple', 'banana', 'avocado', 'cherry', 'blueberry'])
Output
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
Explanation

Bucket each word under its first letter.

Constraints

  • Words are non-empty lowercase strings.
  • Preserve first-seen order within each bucket.

Topics

Dictionariesgrouping

Companies

NetflixLinkedIn

Hints

Hint 1

Loop through words; use `d.setdefault(word[0], []).append(word)`.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.