Sub topic 2
Counting things with Counter
This chapter assumes you know basic Python loops and functions, how to use dict and list, and why dictionary keys must be hashable. You will learn how to create a Counter, how to read counts from it, and which mistakes to avoid.
The problem Counter solves
Counting how often each item appears is a common task. With a plain dict, you need a check for the first time you see each item:
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts) # {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}A Counter is a dict subclass from the collections module that does this loop for you. It maps each item to an integer count.
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
print(counts["dog"]) # 0, and 'dog' is not added to countsThe next chapter covers most_common in detail. Here the focus is on building a Counter and reading from it.
Three ways to create a Counter
The constructor accepts three kinds of input.
from collections import Counter
from_iterable = Counter("banana")
from_mapping = Counter({"red": 2, "blue": 1})
from_keywords = Counter(red=2, blue=1)
print(from_iterable) # Counter({'a': 3, 'n': 2, 'b': 1})
print(from_mapping) # Counter({'red': 2, 'blue': 1})
print(from_keywords) # Counter({'red': 2, 'blue': 1})The input types behave differently:
| Input | What the constructor does |
|---|---|
| An iterable (list, string, generator) | Counts how many times each element appears |
| A mapping (dict, another Counter) | Uses the values as the counts directly |
| Keyword arguments | Uses each name as an item and each value as its count |
Passing a mapping does not count the keys. Counter({"red": 2}) stores a count of 2 for "red". It does not count one key.
An empty Counter() is also valid. You can fill it later by assigning to keys or by using update, which is covered in the next chapter.
Reading counts
Because Counter is a dict, you read a count with square brackets. The difference from a plain dict is what happens with a missing item.
from collections import Counter
c = Counter("banana")
print(c["a"]) # 3
print(c["z"]) # 0, no KeyError
print("z" in c) # False, reading did not insert 'z'
print(len(c)) # 3, the number of distinct itemsA missing item reads as 0 instead of raising KeyError. The lookup does not store anything, so reading never changes the Counter. This differs from defaultdict, which a later chapter covers.
The same rule makes incrementing safe. You can add to an item that was never seen:
from collections import Counter
c = Counter()
c["z"] += 1
c["z"] += 1
print(c) # Counter({'z': 2})Two other reads are useful. sum(c.values()) gives the total number of items counted. On Python 3.10 and later, c.total() does the same thing.
from collections import Counter
c = Counter("banana")
print(sum(c.values())) # 6
print(c.total()) # 6, requires Python 3.10+
print(list(c)) # ['b', 'a', 'n'], keys in first-seen orderKeys keep the order in which they were first added, as in any dict. The printed form of a Counter is different. It lists items from highest count to lowest.
Counting by a rule
The elements you count do not have to be the raw input. A generator expression lets you count a property of each item.
from collections import Counter
names = ["Ada", "Alan", "Grace", "Guido", "Barbara"]
by_initial = Counter(name[0] for name in names)
print(by_initial) # Counter({'A': 2, 'G': 2, 'B': 1})
lengths = Counter(len(name) for name in names)
print(lengths) # Counter({5: 3, 3: 1, 4: 1})This pattern replaces most hand-written counting loops.
Common errors
Unhashable items
Counter stores items as dict keys, so they must be hashable. A list is not.
from collections import Counter
rows = [[1, 2], [1, 2], [3, 4]]
try:
Counter(rows)
except TypeError as error:
print(error) # unhashable type: 'list'
print(Counter(tuple(row) for row in rows))
# Counter({(1, 2): 2, (3, 4): 1})Convert each item to a hashable form, such as a tuple, before counting.
Counting keys instead of values
Passing a dict of counts to Counter copies those counts. If you want to count the values in a dict, pass d.values():
from collections import Counter
colors = {"apple": "red", "cherry": "red", "lime": "green"}
print(Counter(colors.values())) # Counter({'red': 2, 'green': 1})A count of zero is still an entry
Setting a count to 0 does not remove the item. The key stays and len still counts it. Use del to remove an item completely.
from collections import Counter
c = Counter("banana")
c["b"] = 0
print("b" in c, len(c)) # True 3
del c["b"]
print("b" in c, len(c)) # False 2Exercise
Given names = ["Ada", "Alan", "Grace", "Guido", "Barbara"], what does Counter(len(n) for n in names)[7] return, and what is len() of that Counter afterward? Explain why reading key 7 does not change the Counter.
Show answer
The lengths are 3, 4, 5, 5, 7, so the count for 7 is 1 (Barbara has 7 letters), and the Counter has 4 distinct keys: 3, 4, 5, and 7. Reading a key that exists simply returns its count. If you instead read a key that is absent, such as 9, you get 0, and len() stays 4, because Counter returns 0 for missing items without inserting them.