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. Unlike defaultdict, 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 holdsContainerIn this lesson
nothing: seen or notsetthe seen-set
one valuedictsize → position
a group of itemsdefaultdict(list)host → its events
a countCounterword → 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.