Python's standard library includes a package called
collections. It holds data structures that solve common problems more cleanly than raw dictionaries or lists. Today you will meet three: Counter, defaultdict, and namedtuple.Counter
Counting how often each item appears in a list usually takes four lines of manual dictionary work.
collections.Counter does it in one.from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'red']
result = Counter(colors)
print(result)Counter is also handy when merging two Counters: simply add them together with + (plain dictionaries can't be added). It returns the most common elements via .most_common(n) as well.defaultdict
A normal dictionary raises
KeyError when you read a key that is not there. A defaultdict lets you supply a factory so missing keys are created automatically.from collections import defaultdict
groups = defaultdict(list)
for name in ['Alice', 'Bob', 'Carol']:
groups[name[0].lower()].append(name)defaultdict(int) is especially common for accumulating totals, because int() returns 0. You can also use any zero-argument callable as the factory.namedtuple
A plain tuple like
(1, 'Alice') is fine for data, but you cannot tell which position means what. A namedtuple gives fields names while keeping the lightweight, immutable nature of a regular tuple.from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 7)
print(p.x + p.y)namedtuple supports unpacking and indexing just like tuples: p[0], x, y = p. It is also hashable, so you can use instances as dictionary keys or set members. For mutable records with defaults and methods, reach for a dataclass instead.