← All lessons

collections: Counter and defaultdict

Sign in · Sign up

Lesson 11.9

collections gives handy structures:

from collections import Counter, defaultdict

text = "cat and dog and cat"
words = text.split()

counter = Counter(words)
print(counter.most_common(2))

groups = defaultdict(list)
for word in words:
    groups[len(word)].append(word)

# don't copy the example above: the text and the words in the task are different
  • Counter counts repeats: counter[word] gives a number, not an error;
  • most_common(2) — the most frequent pairs;
  • defaultdict(list) creates an empty list itself when the key is still missing.

The check sets the list of words words. Print:

  1. most_common for the first top pairs — the way print shows it;
  2. the repeat count of the most frequent word through counter.most_common(1)[0][1];
  3. how many words appeared count times — with a generator and sum.
Hint

Counter(list) counts repeats itself.

most_common(n) gives a list of pairs from frequent to rare; the most frequent one is the first. To find a pair with a given number of repeats, go through counter.values() and add 1 for every match.