Sub topic 9
Counting and grouping with Counter and defaultdict
This chapter assumes you can create dictionaries, read them with [] and get(), and update entries by assignment. You should also know what a for loop and a list are. The chapter covers the two most common jobs for a dictionary: counting things and grouping things. It shows the manual pattern first, then the tools in collections that remove the boilerplate.
The manual pattern and why it is clumsy
Counting letters in a word needs one decision per item. If the key is new, start at 1. Otherwise, add 1.
word = "banana"
counts = {}
for ch in word:
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}You can shorten this with get() and a default:
word = "banana"
counts = {}
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}Grouping has the same shape, except the value is a list that must exist before you can append to it:
words = ["apple", "avocado", "banana"]
groups = {}
for w in words:
if w[0] not in groups:
groups[w[0]] = []
groups[w[0]].append(w)
print(groups) # {'a': ['apple', 'avocado'], 'b': ['banana']}Both loops spend most of their lines on "does this key exist yet?". Python offers three ways to remove that question: setdefault(), defaultdict, and Counter.
setdefault(): a one-line default
dict.setdefault(key, default) returns the value for key. If the key is missing, it first stores default under that key and then returns it.
words = ["apple", "avocado", "banana"]
groups = {}
for w in words:
groups.setdefault(w[0], []).append(w)
print(groups) # {'a': ['apple', 'avocado'], 'b': ['banana']}setdefault() works on any ordinary dictionary and needs no import. It has one cost: the default expression is evaluated on every call, even when the key already exists. Here [] creates a new empty list for every word, and most of those lists are thrown away. For cheap defaults this does not matter. For expensive ones, prefer defaultdict.
defaultdict: a dictionary that creates missing values
collections.defaultdict is a dict subclass. You give it a default factory, which is any callable that takes no arguments. When you read a missing key with [], the dictionary calls the factory, stores the result under that key, and returns it.
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 factory is called only when a key is missing, so no list is wasted. Common factories are:
| Factory | Default value | Typical use |
|---|---|---|
| `list` | `[]` | Grouping items into lists |
| `set` | `set()` | Grouping unique items |
| `int` | `0` | Counting |
| `float` | `0.0` | Summing amounts |
| `lambda: "n/a"` | `"n/a"` | A custom constant |
| `dict` | `{}` | Two-level nesting |
Here is a defaultdict used for summing:
from collections import defaultdict
sales = [("north", 120), ("south", 80), ("north", 30), ("east", 55)]
totals = defaultdict(int)
for region, amount in sales:
totals[region] += amount
print(dict(totals)) # {'north': 150, 'south': 80, 'east': 55}The line totals[region] += amount reads totals[region] first. For a new region, that read triggers the factory, which returns 0, and the addition then works.
Reading a missing key creates it
The behavior that makes defaultdict convenient also causes the most common bug with it. Any [] read of a missing key inserts that key, even if you only wanted to look.
from collections import defaultdict
seen = defaultdict(list)
print(seen["x"]) # []
print(len(seen)) # 1
print("y" in seen) # False, and `in` does not create the key
print(seen.get("z")) # None, and get() does not create the key
print(len(seen)) # 1Only [] triggers the factory. The in operator and get() do not. If a lookup is meant to be a pure check, use in or get(), or you will grow the dictionary with keys you never intended to store.
Nested defaultdicts
A factory can itself build a defaultdict. Wrapping it in a lambda gives a two-level structure where both levels fill themselves in:
from collections import defaultdict
by_region = defaultdict(lambda: defaultdict(int))
orders = [("north", "apple"), ("north", "pear"), ("north", "apple"), ("south", "pear")]
for region, item in orders:
by_region[region][item] += 1
print({r: dict(items) for r, items in by_region.items()})
# {'north': {'apple': 2, 'pear': 1}, 'south': {'pear': 1}}Converting back to a plain dict
A defaultdict prints with its class name and factory, and it keeps creating keys on read. When you finish building and pass the result elsewhere, convert it with dict(). Do this for output and for code that should not create keys by accident.
from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
print(d) # defaultdict(<class 'int'>, {'a': 1})
plain = dict(d)
print(plain) # {'a': 1}
try:
plain["missing"]
except KeyError:
print("plain dict raises KeyError")Setting d.default_factory = None also turns off the auto-creation on an existing defaultdict, so missing keys raise KeyError again.
Counter: a dictionary specialized for tallies
collections.Counter is a dict subclass that maps items to counts. You can pass it any iterable, and it counts the items.
from collections import Counter
print(Counter("banana")) # Counter({'a': 3, 'n': 2, 'b': 1})
words = "the cat and the hat and the bat".split()
freq = Counter(words)
print(freq) # Counter({'the': 3, 'and': 2, 'cat': 1, 'hat': 1, 'bat': 1})Printing shows the items from most to least common. The underlying dictionary order is still insertion order. The sorted display comes from Counter.__repr__.
Missing keys return zero
Unlike a defaultdict, a Counter returns 0 for a missing key and does not store it:
from collections import Counter
c = Counter("aab")
print(c["z"]) # 0
print("z" in c) # False
print(len(c)) # 2This lets you write c[item] += 1 without a check, and read counts without side effects.
most_common()
most_common(n) returns a list of (item, count) pairs, highest count first. With no argument, it returns all items. Items with equal counts keep the order in which they were first inserted.
from collections import Counter
freq = Counter("the cat and the hat and the bat".split())
print(freq.most_common(2)) # [('the', 3), ('and', 2)]Updating and arithmetic
update() on a Counter adds counts. This differs from dict.update(), which replaces values.
from collections import Counter
a = Counter(red=2, blue=1)
a.update(["red", "green", "green"])
print(a) # Counter({'red': 3, 'green': 2, 'blue': 1})
a.subtract(["red", "red", "red", "red"])
print(a["red"]) # -1subtract() can leave zero or negative counts. Counters also support arithmetic operators. Addition and subtraction with + and - keep only positive results:
from collections import Counter
x = Counter(a=3, b=1)
y = Counter(a=1, b=2)
print(x + y) # Counter({'a': 4, 'b': 3})
print(x - y) # Counter({'a': 2})
print(x & y) # Counter({'a': 1, 'b': 1}) minimum of each count
print(x | y) # Counter({'a': 3, 'b': 2}) maximum of each countThe x - y result drops b because 1 - 2 is not positive. Use subtract() if you need to keep negative counts.
elements() and total()
elements() expands a counter back into an iterator that repeats each item by its count. Items with a count below one are skipped. total() (Python 3.10+) returns the sum of all counts.
from collections import Counter
c = Counter(a=2, b=1)
print(sorted(c.elements())) # ['a', 'a', 'b']
print(c.total()) # 3Choosing between the tools
A short rule of thumb:
- Use
Counterwhen the value is "how many times did this item appear". You getmost_common(), arithmetic, and safe reads of missing keys. - Use
defaultdict(int)ordefaultdict(float)when you add arbitrary amounts, such as sales totals, rather than counting occurrences of one thing. - Use
defaultdict(list)ordefaultdict(set)to group. Choosesetwhen duplicates should collapse. - Use
setdefault()for a quick one-off grouping, when the default is cheap, or when you want to stay with a plaindict.
Edge cases and common errors
Counter counts what it is given
Passing a string counts characters, not words. Passing a list of words counts words. If you want words, call .split() first. A common mistake is passing a single string when you meant a list of items:
from collections import Counter
print(Counter("hello world"))
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
print(Counter("hello world".split()))
# Counter({'hello': 1, 'world': 1})Keys must still be hashable
Counter and defaultdict are dictionaries, so the key rules still apply. Counting lists fails with TypeError. Convert each list to a tuple first:
from collections import Counter
rows = [[1, 2], [1, 2], [3, 4]]
try:
Counter(rows)
except TypeError as exc:
print(exc) # unhashable type: 'list'
print(Counter(tuple(r) for r in rows))
# Counter({(1, 2): 2, (3, 4): 1})The default factory takes no arguments
defaultdict(0) fails, because 0 is not callable. Use int, which returns 0 when called with no arguments. For a constant that is not a type's empty value, use a lambda.
from collections import defaultdict
try:
defaultdict(0)
except TypeError as exc:
print(exc) # first argument must be callable or None
d = defaultdict(lambda: 100)
print(d["x"]) # 100Do not use a mutable constant such as lambda: shared_list unless you mean every key to share the same object.
Zero and negative counts remain in a Counter
A Counter does not delete an item when its count reaches zero. Entries with zero stay visible through items() and len(). To remove them, use unary plus, which keeps only positive counts:
from collections import Counter
c = Counter(a=2, b=1)
c["a"] -= 2
print(c) # Counter({'b': 1, 'a': 0})
print(+c) # Counter({'b': 1})Counter versus a plain dict in comparisons
A Counter is a dict subclass, so equality with a plain dict compares keys and values. In Python 3.10 and later, a Counter treats a missing key and a zero count as equal in == comparisons between two counters, but a comparison with a plain dict does not do that. When mixing the two, convert deliberately and check your Python version before relying on this.
Putting it together: word frequencies by first letter
This example combines both tools. It counts words, then groups the distinct words by first letter, ordered by frequency inside each group.
from collections import Counter, defaultdict
text = "the cat and the hat and the bat sat on the mat"
freq = Counter(text.split())
by_letter = defaultdict(list)
for word, n in freq.most_common():
by_letter[word[0]].append((word, n))
for letter in sorted(by_letter):
print(letter, by_letter[letter])Output:
a [('and', 2)]
b [('bat', 1)]
c [('cat', 1)]
h [('hat', 1)]
m [('mat', 1)]
o [('on', 1)]
s [('sat', 1)]
t [('the', 4)]Because most_common() already sorts by count, each list inside by_letter is in descending order without a second sort.
Exercise
You have events = [("login", "ana"), ("login", "ben"), ("logout", "ana"), ("login", "ana")]. Write code that builds a dictionary mapping each event name to the set of distinct users who triggered it. Then explain why defaultdict(list) would give a different result.
Show answer
Use a defaultdict with set as the factory: from collections import defaultdict usersbyevent = defaultdict(set) for event, user in events: usersbyevent[event].add(user) print(dict(usersbyevent)) # {'login': {'ana', 'ben'}, 'logout': {'ana'}} With defaultdict(list) and append(), "ana" would appear twice under "login", because lists keep duplicates. A set collapses repeated users, so each user is stored once per event.
Exercise
What do Counter("aab")["z"] and defaultdict(int)["z"] each return, and how do the dictionaries differ afterwards?
Show answer
Both return 0. The Counter is unchanged, so "z" in the Counter is still False and its length is still 2. The defaultdict has stored the key "z" with the value 0, so its length grows by one. This is why a read-only check on a defaultdict should use in or get() instead of [].
Exercise
Given a = Counter(x=2, y=1) and b = Counter(x=3), what are a - b and a.subtract(b) followed by a? Why do they differ?
Show answer
a - b returns Counter({'y': 1}). The - operator keeps only positive counts, so x (2 - 3 = -1) is dropped. a.subtract(b) changes a in place and keeps non-positive counts, so a becomes Counter({'y': 1, 'x': -1}).