defaultdict, Counter & most_common
The collections toolbox
Lesson 6 of 20 · 10 min · Module 2: Work with data efficiently
Counting and grouping are everyday tasks. The collections module has ready-made tools that remove a lot of boilerplate.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Group values with defaultdict
- Count with Counter
- Control the order of ties
The idea
defaultdict(list) creates an empty list the first time a key is used, so groups[key].append(item) always works. Counter(items) counts occurrences, and counter.most_common(n) returns the n most frequent items.
from collections import Counter, defaultdict
print(Counter("banana").most_common(2))
groups = defaultdict(list)
groups["b"].append("bob")
print(dict(groups))
01No more "if key not in"
Without defaultdict you write if key not in groups: groups[key] = [] before every append. defaultdict(list) does that automatically on first access.
02Counter is a dict that counts
Counter(["a", "b", "a"]) gives Counter({"a": 2, "b": 1}). It supports addition, subtraction, and most_common().
from collections import Counter
c = Counter(["web", "data", "web"])
print(c["web"], c["sql"])2 003Ties need a rule
most_common keeps equal counts in insertion order, which depends on the input. Sorting by (-count, word) gives a stable, alphabetical tie-break that tests and users can rely on.
Your turn
group_by_length(words) returning a plain dict that maps each word length to the words of that length, in their original order. Write top_words(text, n) returning the n most common lowercase words as (word, count) pairs; ignore punctuation by keeping only letters, digits and apostrophes in words, and break ties alphabetically.What the checks look for
- Groups words by length in order
- Returns a plain dict
- Finds the most common words, ignoring case and punctuation
- Breaks ties alphabetically and keeps apostrophes
Take this with you
defaultdict groups, Counter counts, and an explicit sort key makes results predictable.
Go a little further
Return the percentage share of each top word instead of the raw count.