Write Python. Understand every error.

Open the editor

Python programs · Strings

Python program to count the frequency of words

Counting how often each word appears is the standard use for a dictionary.

Approach

  1. Read a sentence and split it into words.
  2. Keep a dictionary that maps each word to its count.
  3. Print every word with its count.

The program

text = input().lower()
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
for word, count in counts.items():
    print(word, count)

Sample run

Input
the cat and the dog and the bird
Output
the 3
cat 1
and 2
dog 1
bird 1

Run this program in Py-CRAFT

How the code works

counts.get(word, 0) returns the current count, or 0 if the word has not been seen, and the + 1 records the new sighting. Using .get avoids the KeyError that counts[word] would cause for a new word. Dictionaries keep the order in which keys were first added, which is why the output follows the sentence.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: