20/40
Part 3 of 7 · Grouping and countingLearn and do
Count first, then decide
The third pattern counts how often each key appears. Some questions need those counts for the whole input before they can decide about any one item.
A count is a dict from each key to a number
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
counts.get(word, 0) gives 0 for a word you haven't seen yet.
Counter counts in one call, and a missing count is 0
collections.Counter does the same loop in one call, and adds what you usually want next:
from collections import Counter
counts = Counter(words)
print(counts.most_common(2))
print(counts["dog"], "dog" in counts)
print(Counter("listen") == Counter("silent"), Counter("aab") == Counter("abb"))
[('the', 3), ('and', 2)]
0 False
True False
most_common(2)gives the two biggest counts.- A missing key reads as 0, not a
KeyError. Unlikedefaultdict, reading it doesn't add it. - Two Counters are equal when every count matches. That's an anagram test in one line.
Pick the container by what each key holds
| Each key holds | Container | In this lesson |
|---|---|---|
| nothing: seen or not | set | the seen-set |
| one value | dict | size → position |
| a group of items | defaultdict(list) | host → its events |
| a count | Counter | word → how often |
Any of them works anywhere. The right one deletes lines and says what you mean.
In the editor, finish count_words(words) with counts.get(word, 0) + 1. Then write same_letters(a, b): True when the two strings are anagrams, by comparing two Counters.