PythiloLesson 19 of 30 · progress kept in this browser

Grouping and counting

Two dict patterns come up again and again: counting how often each thing appears, and grouping items under a shared key.

from collections import Counter

words = ["ant", "bee", "ape", "bat", "ant"]
counts = Counter(words)
print(counts["ant"], counts["cow"])  # 2 0
print(counts.most_common(1))  # [('ant', 2)]

groups = {}
for w in words:
    groups.setdefault(w[0], []).append(w)
print(groups)
  • Counter is a dict that counts. A missing key reads as 0 instead of raising KeyError.
  • most_common(n) returns the n biggest counts as (item, count) pairs, largest first. Equal counts keep the order in which the items were first seen.
  • d.setdefault(key, []) returns the list stored under key, creating an empty one first if needed, so one line both creates and appends.
  • collections.defaultdict(list) does the same job: a missing key gets a fresh empty list.

Each group keeps the order its items arrived in, which is usually what a reader expects.

Your task

Write group_by_length(words) returning a dict from word length to the list of words of that length, in their original order. Write top_letters(text, n) returning the n most common letters as (letter, count) pairs, ignoring case and skipping anything that is not a letter.

Next: Nested data