Python bootcamp · Lab 21

Word frequency

mediumDictionaries15 minLesson: Dictionaries

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one line of words. Print each distinct word and how many times it appears, one per line, sorted alphabetically.

Each line is the word, a space, then the count. This tallying pattern is the heart of counting, grouping, and histograms.

Input. One line of space-separated words.

Output. Lines of "word count", sorted alphabetically by word.

Examples

Example 1 — Alphabetical order: cat, dog, the.
Input
the cat the dog the
Output
cat 1
dog 1
the 3
Hint
  1. collections.Counter(words) tallies everything in one call.
  2. sorted(counter.items()) orders the pairs alphabetically by word; print each as f"{word} {n}".
Show correct code

Peek only after you have tried. You can still Check your own version.

from collections import Counter
words = input().split()
for word, n in sorted(Counter(words).items()):
    print(f"{word} {n}")
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.