Start learning free

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

Word Frequency in Python: Counting Words in a Sentence

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a dict where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Word Frequency in Python, explained

    Problem overview

    The method wordFrequency receives a string, sentence, made of lowercase words separated by single spaces, and returns a dictionary. Each word of the sentence is a key, and its value is the number of times the word appears. The order of the entries doesn't matter.

    For "the cat and the hat" the result is {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}. For "go go go" it is {'go': 3}: the same word three times is one key with the value 3. A one-word sentence such as "hello" gives {'hello': 1}.

    Approach: split, then count

    The problem has two parts. First, turn the sentence, which is one string, into a list of words. Then count the items of that list with a dictionary, the same pattern that counts letters in a string.

    The first part is done by the string method split(). Called with no argument, it cuts the string at whitespace and returns a list of the pieces. The second part is the counting loop: a word that is already a key gets its count raised, and a new word starts at 1.

    Step by step

    1. Split the sentence. words = sentence.split() gives ['the', 'cat', 'and', 'the', 'hat'] for the first example.
    2. Create an empty dictionary named counts. No word has been counted yet.
    3. Loop over words with for word in words. Every word adds 1 to its own count, so each gets a turn.
    4. Raise the count of a known word. If word in counts, run counts[word] += 1.
    5. Start a new word at 1 in an else: counts[word] = 1. Adding 1 to a key that doesn't exist yet would raise a KeyError.
    6. Return counts after the loop.

    The solution in Python

    class Solution:
        def wordFrequency(self, sentence: str) -> Dict[str, int]:
            words = sentence.split()
            counts = {}
            for word in words:
                if word in counts:
                    counts[word] += 1
                else:
                    counts[word] = 1
            return counts
    

    Python details to keep in mind:

    • split() without an argument treats any run of whitespace as one separator and ignores leading and trailing whitespace. For "the cat and", with two spaces between "cat" and "and", the result is {'the': 1, 'cat': 1, 'and': 1}, with no empty-string key. split(" ") would behave differently there: it returns an empty string for every extra space.
    • Keys are compared exactly. The words are all lowercase here. In general, "The" and "the" are different keys, so text with mixed case needs lower() first.
    • Strings can be keys. Strings are immutable, so Python allows them as dictionary keys, as it does for numbers and tuples. Lists can't be keys.
    • The same pattern counts anything. Only the source of the items changes: letters of a string, words of a sentence, numbers of a list.

    Edge cases and common mistakes

    • Counting the sentence instead of the words. Looping over sentence directly visits single characters, so the keys would be letters and spaces. The split() call comes first.
    • Forgetting the first-time case. Without the else branch, the first word raises KeyError.
    • Treating the loop variable as the count. The loop variable word is the word. Its count lives in counts[word].
    • One word. "hello" splits into a one-item list, and the result is {'hello': 1}.

    Testing

    • "the cat and the hat" gives {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}.
    • "go go go" gives {'go': 3}.
    • "hello" gives {'hello': 1}.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free