Start free

Intermediate · Dictionaries · 133 of 264

Word frequency

Count how often each word appears (ignore capital letters). Print the words from the most to the least common; equally common words in alphabetical order.

Input: one line of words. Output: one line per word: <word> <count>

Examples

Input
the cat and the hat
Output
the 2
and 1
cat 1
hat 1
Input
a A a
Output
a 3
Input
one two three
Output
one 1
three 1
two 1

One more test checks other inputs when you press Check.

Stuck? The idea behind dictionaries

A dictionary links keys to values, like words to meanings: ages["Ann"] = 12. Looking up a key is fast, however big it is.

.get(key, 0) gives a default when the key isn't there; looping over a dictionary gives its keys, .items() gives keys and values together.

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

Watch for: Reading a key that isn't there stops the program with a KeyError: check with in, or use .get().

All the dictionaries exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More dictionaries exercises