Start learning free

LESSON 228 OF 287 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Group Words by First Letter in Python: A Dictionary of Lists

Practice Read the full explanation

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

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Group Words By First Letter in Python, explained

    Problem overview

    The method groupByFirstLetter receives a list of lowercase words and returns a dictionary. Each key is a first letter, written as a one-character string, and its value is the list of all the words that start with that letter. Inside each group the words keep the order they have in the input. The order of the dictionary's entries doesn't matter.

    For ["apple", "banana", "avocado", "blueberry", "cherry"] the result is {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}. For ["dog", "cat", "deer", "cow", "duck"] it is {'d': ['dog', 'deer', 'duck'], 'c': ['cat', 'cow']}. A word that appears twice is listed twice in its group.

    Approach: a dictionary whose values are lists

    Counting with a dictionary stores a number under each key. Grouping works the same way, except that each value is a list that collects items. For every word, find its group, creating the group first if this is the first word with that letter, and add the word to it.

    One pass over the words is enough, since each word belongs to exactly one group. The words arrive in input order and are appended at the end of their group's list, so each group keeps that order.

    Step by step

    1. Create an empty dictionary named groups. Later, keys are letters and values are lists of words.
    2. Loop over words with for word in words.
    3. Take the first letter: first = word[0]. It is the key of the group this word belongs to.
    4. Create the group when it is missing. if first not in groups: is true when the key is absent, and its body sets groups[first] = []. The first word with a new letter starts the group. Later words with the same letter find it already there.
    5. Append the word with groups[first].append(word). This line sits after the if, so it runs for every word, whether the group was just created or already existed.
    6. Return groups after the loop.

    The solution in Python

    class Solution:
        def groupByFirstLetter(self, words: List[str]) -> Dict[str, List[str]]:
            groups = {}
            for word in words:
                first = word[0]
                if first not in groups:
                    groups[first] = []
                groups[first].append(word)
            return groups
    

    Python details to keep in mind:

    • word[0] is a string. Indexing a string gives a one-character string, which is what the keys should be. It works because every word has at least one letter. On an empty string, ""[0] raises IndexError: string index out of range.
    • not in is the opposite of in. first not in groups is true when first is not a key.
    • groups[first] is the list itself. It isn't a copy, so appending to it changes the list stored in the dictionary. There is no need to assign it back.
    • Each group needs its own list. Because [] is evaluated each time the if body runs, every letter gets a fresh list. Sharing one list between groups would mix the words up.
    • A built-in shortcut. groups.setdefault(first, []).append(word) or collections.defaultdict(list) replaces the if. The explicit check shows the two cases clearly, and it is how most beginners first write it.

    Edge cases and common mistakes

    • Appending to a missing group. Without the if, groups[first].append(word) raises KeyError on the first word of each letter.
    • Resetting the group every time. If groups[first] = [] ran for every word, instead of only when the key is missing, each group would end up holding just its last word. Keep that line inside the if.
    • Repeated words. ["no", "net", "no"] gives {'n': ['no', 'net', 'no']}: nothing is removed, and the order is kept.
    • One word. ["hello"] gives {'h': ['hello']}.

    Testing

    • ["apple", "banana", "avocado", "blueberry", "cherry"] gives {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}.
    • ["dog", "cat", "deer", "cow", "duck"] gives {'d': ['dog', 'deer', 'duck'], 'c': ['cat', 'cow']}.
    • ["hello"] gives {'h': ['hello']}.
    • ["no", "net", "no"] gives {'n': ['no', 'net', 'no']}.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free