Python · Level 2 Data

Counter & defaultdict

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)

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']}

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.

solution.py
Test Suites Pending
Stdout