Sub topic 9
Counting and grouping with Counter and defaultdict
This chapter assumes you can read and write dictionaries, use get() and in, and know that d[key] raises KeyError when the key is missing. Counting and grouping are the two jobs where that KeyError gets in your way most often.
The manual pattern and its cost
To count items, you must handle the first time you see each key. With a plain dictionary, get() with a default does this:
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}This works, but you repeat the same lookup-or-default step every time. The standard library's collections module has two tools that remove it.
Counter: tallying items
Counter is a dict subclass that counts hashable items. Pass it any iterable and it builds the tallies for you.
from collections import Counter
print(Counter("banana")) # Counter({'a': 3, 'n': 2, 'b': 1})A Counter behaves like a dictionary with a few additions:
- A missing key returns
0instead of raisingKeyError. The lookup does not add the key. most_common(n)returns thenhighest counts as a list of(item, count)pairs.update(iterable)adds to the existing counts. Unlikedict.update(), it does not replace them.
from collections import Counter
c = Counter("banana")
print(c["z"]) # 0
print(c.most_common(2)) # [('a', 3), ('n', 2)]
c.update("band")
print(c["a"]) # 4defaultdict: creating values on demand
defaultdict takes a factory, a callable with no arguments. When you read a key that is missing, it calls the factory, stores the result under that key, and returns it. Grouping is the typical use, with list as the factory:
from collections import defaultdict
groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
groups[word[0]].append(word)
print(dict(groups)) # {'a': ['apple', 'avocado'], 'b': ['banana']}The first time groups["a"] is read, an empty list is created and stored. The append() then works on it. Other common factories are int (starts at 0, so d[k] += 1 counts), set (unique groups) and dict (nested mappings).
setdefault on a plain dict
If you only need grouping in one place, a plain dict has setdefault(key, default). It returns the existing value, or stores and returns the default if the key is absent.
groups = {}
for word in ["apple", "avocado", "banana"]:
groups.setdefault(word[0], []).append(word)
print(groups) # {'a': ['apple', 'avocado'], 'b': ['banana']}Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Checking `d[k]` on a `defaultdict` to test presence | The key is created as a side effect | Use `k in d` |
| Passing a value instead of a factory, as in `defaultdict(0)` | `TypeError: first argument must be callable or None` | Pass `int` |
| Expecting `Counter.update()` to replace counts | Counts are added | Assign `c[k] = n` to set a count |
| Passing a list of keys and expecting a `Counter` to count its items | It counts the list's elements, which must be hashable | Convert unhashable items, such as lists, to tuples first |
Choosing between them
Use Counter when the result is a tally of items you can iterate over, because you also get most_common(). Use defaultdict when each key needs a container or a custom starting value. Both are ordinary dictionaries in every other respect, so items(), in and len() all work as you expect. Convert with dict(...) if you want to hand a plain dictionary to other code.
Exercise
Given words = ["to", "be", "or", "not", "to", "be"], write code that (1) uses Counter to find the most frequent word and its count, and (2) uses defaultdict to group the words by length. What does each part produce?
Show answer
from collections import Counter, defaultdict words = ["to", "be", "or", "not", "to", "be"] print(Counter(words).mostcommon(1)) # [('to', 2)] bylen = defaultdict(list) for w in words: bylen[len(w)].append(w) print(dict(bylen)) # {2: ['to', 'be', 'or', 'to', 'be'], 3: ['not']} "to" and "be" both appear twice. Counter's most_common orders ties by first appearance, so "to" is returned first.