Start learning free

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

Letter Count in Python: Counting with a Dictionary

Practice Read the full explanation

Given a string word, return a dict that maps each letter of word to the number of times it appears in word.

Every letter of word is a key, and its value is how many times that letter appears. The order of the entries doesn't matter.

 

Example 1:

Input: word = "banana"
Output: {"b": 1, "a": 3, "n": 2}
Explanation: "b" appears once, "a" three times and "n" twice.

Example 2:

Input: word = "hello"
Output: {"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: "l" appears twice; every other letter appears once.

Example 3:

Input: word = "a"
Output: {"a": 1}
Explanation: A single letter appears once.

 

Constraints:

  • word has at least one letter.
  • word is made of lowercase English letters, a to z.
  • Only the letters of word are keys: a letter that doesn't appear has no entry.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Letter Count in Python, explained

    Problem overview

    The method letterCount receives a string, word, and returns a dictionary that maps each letter of the word to the number of times it appears. Only letters that occur in the word get an entry, and the order of the entries doesn't matter.

    For "banana" the result is {'b': 1, 'a': 3, 'n': 2}. For "hello" it is {'h': 1, 'e': 1, 'l': 2, 'o': 1}, and for "a" it is {'a': 1}.

    Approach: a counting dictionary

    A dictionary stores key-value pairs, so it is the natural tool for "how many of each". Each letter is a key, and its value is how many times that letter has been seen so far. The loop visits the letters one at a time. A letter that is already a key gets its count raised by one. A letter that is new gets an entry that starts at 1.

    The two cases have to be handled separately because reading a key that isn't in a dictionary is an error, as the next section shows.

    Step by step

    1. Create an empty dictionary named counts. Nothing has been counted yet.
    2. Loop over the letters with for letter in word. A for loop over a string visits its characters one by one, just as a loop over a list visits its items.
    3. Check whether the letter is already a key with if letter in counts. If it is, add 1 with counts[letter] += 1.
    4. Handle the first sighting in an else: counts[letter] = 1. Assigning to a key that doesn't exist yet creates it.
    5. Return counts after the loop.

    Watching the dictionary grow

    For "banana", the dictionary after each letter looks like this:

    lettercounts afterwards
    b{'b': 1}
    a{'b': 1, 'a': 1}
    n{'b': 1, 'a': 1, 'n': 1}
    a{'b': 1, 'a': 2, 'n': 1}
    n{'b': 1, 'a': 2, 'n': 2}
    a{'b': 1, 'a': 3, 'n': 2}

    The solution in Python

    class Solution:
        def letterCount(self, word: str) -> Dict[str, int]:
            counts = {}
            for letter in word:
                if letter in counts:
                    counts[letter] += 1
                else:
                    counts[letter] = 1
            return counts
    

    Details worth knowing:

    • in checks keys. letter in counts asks whether letter is a key of the dictionary. It never looks at the values.
    • A missing key raises KeyError. Running counts["x"] += 1 on an empty dictionary stops with KeyError: 'x', because += has to read the old value first. That is why the first sighting needs its own branch.
    • Dictionaries keep insertion order. The result lists letters in the order they first appeared. The lesson doesn't depend on that order, but it explains why the printed dictionaries above start with 'b' for "banana".
    • Shorter forms exist. counts[letter] = counts.get(letter, 0) + 1 replaces the if and else, and collections.Counter(word) does the whole job. Writing the branches by hand first makes both easier to understand.

    Edge cases and common mistakes

    • Adding to a missing key. Skipping the else branch, or writing only counts[letter] += 1, raises a KeyError on the first letter.
    • Starting every count at 0 instead of 1. If the first sighting sets the value to 0, every count ends one too low.
    • Returning inside the loop. The function would give back a dictionary with only the first letter.
    • Single letter. "a" gives {'a': 1}: the loop runs once and only the else branch is used.

    Testing

    • "banana" gives {'b': 1, 'a': 3, 'n': 2}.
    • "hello" gives {'h': 1, 'e': 1, 'l': 2, 'o': 1}.
    • "a" gives {'a': 1}.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free