TwiddleLab / Code / Build with Python
Counting with a Dictionary
What you will learn
- The counting pattern: counts[w] = counts.get(w, 0) + 1.
- d.get(key, default) gives the value, or the default if the key isn't there: no KeyError.
- A new key starts at 0 and becomes 1; a known key just goes up by 1.
- Counting pairs of words is how the simplest text predictors guess the next word.
How the lesson goes
Which reaction does your group chat use most?
Skim 30 messages, then tap your bet.
Count the first 10 by hand, with drawers.
Drop each word into its drawer for +1. A word you haven't seen gets a new drawer: it starts at 0, then +1.
Now let the code count all 30.
One line does both moves: new drawer at 0, then +1.
The counting pattern.
d.get(key, default) reads a value safely: if the key isn't there, you get the default instead of a KeyError.
The counting pattern is counts[w] = counts.get(w, 0) + 1: a new word starts from 0, a known word from its count.
Put it in a loop over anything (words, letters, votes, songs) and it counts them all.
This counter crashes on the very first word. Fix it.
Run it, read the error, then change the right side of line 4.
Build a letter counter for mississippi.
Same pattern, but over letters. Put the lines in order.
Find the winner in your counter's drawers.
A pointer walks the drawers. Keep a drawer if it beats the best so far, otherwise skip.
Count words, or count pairs of words?
Run both counters. Then tap the one that can tell what usually comes after like.
Fill the drawers: what does counts hold at the end?
Drag a number into each drawer, then Check.
Back to the chat. Now make it 10,000 messages.
Pick bigger chats. The same three lines count them all.
Previous lesson: Dictionaries: Labels, Not Numbers · Next lesson: Debugging Like a Detective · Part of the course: Build with Python
Lessons are interactive and need JavaScript. Turn it on to play them.