Counting with a dictionary
After this: Write the five-line loop that counts how often each word appears.
On this page · 6 sections · 3 checks
How many times does each word appear in a text? Which letter is the most common in a word? Which product was ordered most often? Each of these is a count, and there is one count for each different thing.
In Repeating you counted one thing with a loop and a box. Here you need a count for every word, and you do not know the words in advance. A dictionary holds them: the word is the key, and its count is the value.
By hand
Take the cat and the hat, five words. Start with an empty dictionary and go through the words one at a time.
the: not a key yet. Add the pair the: 1.cat: new. Add cat: 1.and: new. Add and: 1.the: already a key, with the value 1. Change it to 2.hat: new. Add hat: 1.
Four pairs at the end: the: 2, cat: 1, and: 1, hat: 1. Five words went in, but a repeated word changes its pair instead of adding one. The number of pairs is the number of different words.
The long way
The last lesson had both halves of this: ask whether the key is there, then either change its value or add a pair.
text = "the cat and the hat"counts = {}for word in text.split(" "): if word in counts: counts[word] = counts[word] + 1 else: counts[word] = 1print(counts["the"])run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
text.split(" ") cuts the text at the spaces and gives back the five words, as Strings showed, and the loop goes through them. Line 48 asks whether the word is a key already. If so, line 59 adds one to its count. If not, line 711 starts it at 1.
The short way
The two branches do nearly the same thing: take the count so far, add one, put it back. The only difference is what "the count so far" means for a new word: 0. That is exactly what reading with a fallback gives. So the two branches collapse into one line:
counts[word] = counts.get(word, 0) + 1counts.put(word, counts.getOrDefault(word, 0) + 1);Read it from the inside out.
- counts.get(word, 0)counts.getOrDefault(word, 0) is the count so far, or 0 when this word is new.
+ 1makes it one more.- The result is put back under the key
word. When the word was new, that adds the pair; when it was not, that changes the value.
- Run the programRun it and watch the box counts grow. It gains a pair for each new word, and when the word the comes round again its count goes from 1 to 2.
text = "the cat and the hat"counts = {}for word in text.split(" "): counts[word] = counts.get(word, 0) + 1print(counts["the"])print(counts["hat"])print(len(counts))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
These are the most useful five lines in this learning path: an empty dictionary, a loop over the pieces, and the one line that counts. Change what the loop goes over, and the same lines count letters, names, or orders.
Change the text to a longer sentence, or print the count of a different word, and run again.
Printing the whole count
text = "the cat and the hat"counts = {}for word in text.split(" "): counts[word] = counts.get(word, 0) + 1print(counts){'the': 2, 'cat': 1, 'and': 1, 'hat': 1}String text = "the cat and the hat";HashMap<String, Integer> counts = new HashMap<>();for (String word : text.split(" ")) { counts.put(word, counts.getOrDefault(word, 0) + 1);}System.out.println(counts);{the=2, and=1, cat=1, hat=1}Check yourself
The loop counts the words of the cat and the hat. How many pairs does counts hold when the loop has finished?
The counting line is missing. Complete it so that the program prints 2 for the and 1 for cat. Use the fallback form, so that a new word starts at 1.
text = "the cat and the hat"counts = {}for word in text.split(" "): ____________________ # ← add one to this word's countprint(counts["the"])print(counts["cat"])String text = "the cat and the hat";HashMap<String, Integer> counts = new HashMap<>();for (String word : text.split(" ")) { ____________________ // ← add one to this word's count}System.out.println(counts.get("the"));System.out.println(counts.get("cat"));The same loop, counting letters instead of words. What does this print?
word = "banana"counts = {}for ch in word: counts[ch] = counts.get(ch, 0) + 1print(counts["a"])print(len(counts))String word = "banana";HashMap<Character, Integer> counts = new HashMap<>();for (char ch : word.toCharArray()) { counts.put(ch, counts.getOrDefault(ch, 0) + 1);}System.out.println(counts.get('a'));System.out.println(counts.size());Honesty notes
- Write the counting loop: an empty dictionary, then one line per word that adds one to that word's count.
- Read a count that may not exist yet with a fallback of 0, so the first time a word is seen it starts at 1.
- Say that a repeated word changes its pair instead of adding a new one.
- Count letters, words or anything else that can be a key.