Start learning free

LESSON 229 OF 673 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Group Words by First Letter

Practice

Given a list words of lowercase words, group the words by their first letter. Return a dict where each key is a first letter, written as a one-character string, and its value is a list of all the words that start with that letter.

Inside each group, keep the words in the order they have in words. The order of the entries in the dict doesn't matter.

Example 1:

Input: words = ["apple", "banana", "avocado", "blueberry", "cherry"]
Output: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}
Explanation: "apple" and "avocado" start with "a", "banana" and "blueberry" start with "b", and "cherry" is alone under "c".

Example 2:

Input: words = ["dog", "cat", "deer", "cow", "duck"]
Output: {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}
Explanation: "dog" comes before "deer" and "duck" in words, so it comes first in the "d" group too.

Example 3:

Input: words = ["hello"]
Output: {"h": ["hello"]}
Explanation: One word makes one group.

Rules:

  • words has at least one word.
  • Every word has at least one letter and only lowercase letters a-z.
  • A word that appears more than once in words appears as many times in its group.
STEP 1 OF 6
    Ctrl + Enter to check