Playground / Counting Words with a Dictionary

Build a word histogram with counts.get

Counting Words with a Dictionary

Interactive lab

Try it: Counting Words with a Dictionary

The py4e histogram pattern: split each line into words, count them with counts[word] = counts.get(word, 0) + 1, then find the most common word with a max loop or by sorting (count, word) tuples in reverse.

How it works

  1. Optionally remove punctuation with str.translate and lower-case the line, then split() it into words.
  2. For each word: counts.get(word, 0) returns the current count or 0 for a new word; store it plus one (or the if word not in counts form).
  3. A dict remembers insertion order: a word's position is fixed the first time it is seen.
  4. Max loop: keep the word whose count is strictly larger than the best so far (the first word wins a tie).
  5. Or build [(count, word) …], sort with reverse=True (ties ordered by the word, reversed) and slice [:N].

Default run (25 steps): Start with an empty dict. The text has 3 lines. … [:3] keeps the top 3: [(5, 'the'), (2, 'sat'), (2, 'on')].

Simplified: Printable-ASCII text up to 320 characters, 8 lines and 60 words, typed in the lab instead of read from a file or URL.

Educational simulation

Loading the simulation…