Overview
Counting and grouping are everyday tasks. The collections module turns them into one-liners.
- Counter counts items and finds the most common ones
- defaultdict creates missing keys automatically
- most_common(n)
Short Course
Counter counts anything iterable; defaultdict gives every new key a
starting value, so you can append or add without checking first.
from collections import Counter, defaultdict
Counter("banana").most_common(2) # [('a', 3), ('n', 2)]
by_letter = defaultdict(list)
for word in ["apple", "avocado", "kiwi"]:
by_letter[word[0]].append(word)
# {'a': ['apple', 'avocado'], 'k': ['kiwi']}
Task
Write top_words(text, n) that returns the n most common words as
(word, count) pairs. Ignore case, and remove . , ! ? from the ends of
words.
Test Suites
Pending
Stdout