Sub topic 11
Beyond the basics: namedtuple, Counter, defaultdict, and deque
This chapter assumes you know list, tuple, dict, and set, including mutability and hashability, and that you can read a short loop or function. The standard library's collections module offers variants of these four types. Each one removes a pattern you would otherwise write by hand. You do not need them often, but you should recognize when one fits.
When the basic types start to strain
Four situations come up repeatedly:
- A tuple used as a record, where
row[2]tells the reader nothing. - A dict used to count items, with an
if key in dcheck before every update. - A dict whose values are lists, with the same "create the list if missing" check.
- A list used as a queue, where removing from the front is slow.
Each situation has a specialized type.
namedtuple: a tuple with field names
A namedtuple creates a tuple subclass whose positions also have names. It stays immutable, hashable when its fields are hashable, and it unpacks like any tuple.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p[1]) # 3 4
x, y = p # unpacking still works
print(p._replace(x=10)) # Point(x=10, y=4)
print(p) # Point(x=3, y=4)_replace returns a new tuple, because the original cannot change. Because a Point is hashable, it works as a dict key or set element, as the hashability chapter described.
Counter: counting without the boilerplate
A Counter is a dict subclass that maps items to counts. It builds the counts from any iterable in one call.
from collections import Counter
words = "a b a c b a".split()
counts = Counter(words)
print(counts) # Counter({'a': 3, 'b': 2, 'c': 1})
print(counts.most_common(2)) # [('a', 3), ('b', 2)]
print(counts["z"]) # 0, a missing item counts as zero
counts["c"] += 5
print(counts["c"]) # 6Looking up a missing item returns 0 and does not raise KeyError. Unlike defaultdict, a plain lookup does not add the key.
defaultdict: grouping without existence checks
A defaultdict takes a factory function. When you read a missing key, it 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", "blueberry", "cherry"]:
groups[word[0]].append(word)
print(dict(groups))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Without it, you would write groups.setdefault(word[0], []).append(word) or an explicit if check. Other common factories are int (a default of 0), set, and dict.
deque: fast operations at both ends
A list is fast at its right end. Inserting or removing at the left end moves every other element, so the cost grows with the list's length. A deque (double-ended queue) does both ends in constant time. It also accepts a maxlen, which drops the oldest items automatically.
from collections import deque
q = deque([1, 2, 3])
q.appendleft(0)
print(q.popleft()) # 0
print(q) # deque([1, 2, 3])
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
print(recent) # deque([2, 3, 4], maxlen=3)The trade-off is indexing. q[0] and q[-1] are fast, but q[len(q) // 2] walks through the deque, so it is slower than the same index on a list. If you index into the middle often, keep a list.
How they relate to the four basic types
| Type | Built on | Main gain | Main cost |
|---|---|---|---|
| `namedtuple` | tuple | Readable field names | Slightly more setup than a plain tuple |
| `Counter` | dict | Counting and `most_common` | Keys must be hashable, as in any dict |
| `defaultdict` | dict | No missing-key handling | Reads can insert keys |
| `deque` | sequence | Fast operations at both ends | Slower indexing in the middle |
A related type from earlier chapters, frozenset, belongs in the same family. It is a hashable set, so it suits composite dict keys.
Choosing quickly
Start with the basic type and switch only when you notice the pattern. If you write the same if key not in d check three times, use defaultdict or Counter. If a tuple has more than two or three fields, use namedtuple. If you call pop(0) or insert(0, x) on a list in a loop, use deque.
Exercise
You read log lines and want, for each user name, the list of pages that user visited, in order. Which type fits best, and what is the one line that adds a page for a user?
Show answer
Use defaultdict(list). Create it with visits = defaultdict(list), then add a page with visits[user].append(page). The list is created automatically the first time a user appears, and appending keeps the visit order.
Exercise
A worker keeps only the last 100 events it received and discards older ones. Which collection fits, and how do you create it?
Show answer
Use a deque with a maximum length: events = deque(maxlen=100). Each events.append(e) adds to the right end and drops the oldest item from the left once there are 100 items.