Browse topics

Counter and defaultdict

Version
3.14
Since
3.1
Review
Draft

Summary#

Counter is a dictionary subclass that counts hashable items and returns zero for a missing one. defaultdict calls a factory to create the value when [] reads a missing key.

Syntax#

python
counts = Counter(iterable)
counts.most_common(n)
counts.total()
groups = defaultdict(list)
groups[key].append(item)

Example#

python
from collections import Counter, defaultdict

counts = Counter("to be or not to be".split())
print(counts.most_common(2))
print(counts["missing"], counts.total())

by_length = defaultdict(list)
for word in counts:
    by_length[len(word)].append(word)
print(dict(by_length))

print(by_length.get(9), 9 in by_length)
print(by_length[9], 9 in by_length)

stock = Counter(apple=3, pear=1)
used = Counter(apple=1, pear=2)
print(stock - used)
stock.subtract(used)
print(stock)

Expected output#

Text
[('to', 2), ('be', 2)]
0 6
{2: ['to', 'be', 'or'], 3: ['not']}
None False
[] True
Counter({'apple': 2})
Counter({'apple': 2, 'pear': -1})

Common mistakes#

Reading groups[key] on a defaultdict inserts a missing key. Use get or in for a lookup that must not change the mapping. The - operator on counters drops zero and negative results, while subtract keeps them.

Version applicability#

defaultdict is available from Python 3.0. Counter was added in 3.1, Counter.subtract in 3.2, and its insertion-order guarantee in 3.7. The example requires Python 3.10 or later for Counter.total.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0