Sub topic 1
Why the `collections` Module Exists
Prerequisites
You should know basic Python syntax, loops, functions, lists, and dictionaries. You should also understand that dictionary keys must be hashable, such as strings, numbers, or tuples.
Specialized containers
Python’s collections module provides container types for common patterns. A plain dict stores key-value pairs, but counting items or grouping values often requires extra checks and code. Specialized containers package those patterns into clear operations.
This chapter focuses on Counter, a dictionary-like object for counting hashable items.
> callout note > Counter is a subclass-like mapping designed for counts. Its values are normally integers, but it does not enforce that type. >
Counting things with `Counter`
Create a Counter from an iterable, such as a list or the result of split(). Each distinct item becomes a key, and its value is the number of occurrences.
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"]) # 0Reading a missing item returns 0; the lookup does not add that item to the counter. Counter requires hashable items because it uses them as dictionary keys.
Counter operations
most_common(n) returns the n highest counts first. update() adds counts from another iterable or counter. subtract() decreases counts and can leave zero or negative values.
from collections import Counter
a = Counter(apples=3, pears=1)
b = Counter(apples=1, pears=2)
a.update(b)
print(a) # Counter({'apples': 4, 'pears': 3})
a.subtract(Counter(apples=2, pears=4))
print(a) # Counter({'apples': 2, 'pears': -1})Counter arithmetic has useful multiset behavior:
a + badds counts and drops results at or below zero.a - bsubtracts counts and drops results at or below zero.a & bkeeps the smaller count for each item.a | bkeeps the larger count for each item.
Exercise
Which operation returns the two most frequent words in a Counter named counts?
Show answer
counts.most_common(2).