Sub topic 11
Beyond the basics: namedtuple, Counter, defaultdict, and deque
The four core collections cover most tasks. Some jobs come up so often that the standard library has a specialized version that is shorter, safer, or faster. This chapter covers four of them: namedtuple, Counter, defaultdict, and deque. It also revisits frozenset.
Each one is a refinement of a type you already know. Choosing it is mostly about recognizing a pattern in your code and replacing hand-written boilerplate.
Prerequisites
This chapter assumes you have read the earlier chapters of this tutorial or know the following:
- Lists and tuples are ordered. Lists are mutable and tuples are not.
- Dict keys and set elements must be hashable.
- Dict and set lookups take roughly constant time. Searching a list takes time proportional to its length.
- Basic function and loop syntax, and how to import from a module.
All examples run on Python 3.8 or later. Counter.total() needs 3.10 or later, and the text marks it where it appears.
namedtuple: a tuple with field names
A tuple is a good fixed record, but row[2] tells the reader nothing. A namedtuple is a tuple subclass that adds names to the positions. It is still immutable, still ordered, and still supports unpacking and indexing.
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) # Point(x=3, y=4)
print(p == (3, 4)) # True, because it is a tuple underneath
print(p._replace(x=10)) # Point(x=10, y=4), a new object
print(p._asdict()) # {'x': 3, 'y': 4}
try:
p.x = 99
except AttributeError:
print("fields are read-only")_replace does not change p. It returns a new tuple, which is the usual way to "modify" an immutable record. The leading underscore on _replace and _asdict does not mean "private". It keeps these method names from colliding with your field names.
The typed class syntax
For records with defaults and type hints, use typing.NamedTuple. It builds the same kind of object with a class body.
from typing import NamedTuple
class Employee(NamedTuple):
name: str
dept: str = "unassigned"
e = Employee("Ana")
print(e) # Employee(name='Ana', dept='unassigned')
print(e.dept) # unassignedGotchas
- A namedtuple compares equal to a plain tuple with the same values.
Point(1, 2) == (1, 2)isTrue, and so isPoint(1, 2) == Vector(1, 2)for two different namedtuple types with the same field values. If you need to tell record types apart, compare types as well, or use a class. - A namedtuple is hashable only if every field is hashable. The shallow immutability from the pitfalls chapter applies here too. A field that holds a list makes the record mutable in practice and unhashable.
- Field names must be valid identifiers and cannot start with an underscore. The
rename=Trueoption replaces bad names with positional ones.
Use a namedtuple when you have a small, fixed set of fields that never change after creation, such as coordinates, database rows, or return values. If you need mutation or methods with state, a regular class or a dataclass fits better.
Counter: a dict specialized for counting
Counting items is the most common dict pattern, and the hand-written version is clumsy.
words = "the cat and the hat and the bat".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1Counter is a dict subclass that does this for you. It accepts any iterable and maps each element to the number of times it appears.
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts["the"]) # 3
print(counts["dog"]) # 0, a missing key gives 0 instead of KeyError
print("dog" in counts) # False, reading a missing key does not insert it
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
counts.update(["cat", "cat"]) # update ADDS to counts, unlike dict.update
print(counts["cat"]) # 3Two details matter. First, Counter.update adds counts, whereas dict.update replaces values. Second, a missing key returns 0 without being stored, so lookups do not grow the counter.
Counter arithmetic
Counters behave like multisets (sets that allow repeats). They support these operators:
from collections import Counter
a = Counter("aabbc") # a:2, b:2, c:1
b = Counter("abbd") # a:1, b:2, d:1
print(dict(a + b)) # {'a': 3, 'b': 4, 'c': 1, 'd': 1}
print(dict(a - b)) # {'a': 1, 'c': 1}, zero and negative counts are dropped
print(dict(a & b)) # {'a': 1, 'b': 2}, the minimum of each count
print(dict(a | b)) # {'a': 2, 'b': 2, 'c': 1, 'd': 1}, the maximum of each countThe - operator discards results that are zero or negative. If you need to keep negative counts, use the subtract method, which modifies the counter in place.
Gotchas
most_common()with no argument returns every element, sorted by count. Elements with equal counts keep the order in which they were first seen.len(counts)is the number of distinct elements. The sum of all counts issum(counts.values()), orcounts.total()on Python 3.10 or later.- Counter keys must be hashable, for the same reason as any dict key.
Counteris for counts. If you want to group the items themselves, usedefaultdict(list), shown next.
defaultdict: no more missing-key checks
Another common pattern is grouping. You want a dict whose values are lists, and you want to append to the list for a key that may not exist yet. A plain dict forces a check every time:
groups = {}
for w in ["apple", "avocado", "banana"]:
if w[0] not in groups:
groups[w[0]] = []
groups[w[0]].append(w)A defaultdict takes a factory, which is a function that takes no arguments and returns the starting value. When you look up a missing key, the dict calls the factory, stores the result under that key, and returns it.
from collections import defaultdict
by_letter = defaultdict(list)
for w in ["apple", "avocado", "banana", "blueberry", "cherry"]:
by_letter[w[0]].append(w)
print(dict(by_letter))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Common factories are list, set, int (which gives 0), and lambda: ... for anything else. Pass the function itself, not a call to it. defaultdict(list) is correct and defaultdict(list()) raises a TypeError.
The side effect of a lookup
Reading a missing key creates it. This is the main way defaultdict surprises people.
from collections import defaultdict
d = defaultdict(int)
print("x" in d) # False
d["x"] # a plain read...
print("x" in d) # True, ...inserted the key with value 0
print(d.get("y")) # None, get does not call the factory
print("y" in d) # FalseIf you only want to check or read, use in or .get(). After you finish building the structure, convert it with dict(d) if you want to stop new keys from appearing by accident.
Counter or defaultdict(int)?
Both can count. Prefer Counter when counting is the whole point, because you get most_common, arithmetic, and a constructor that counts an iterable in one call. Prefer defaultdict(int) when the counting is part of a larger loop that also does other things per key.
deque: a list built for both ends
A list is fast at the right end and slow at the left. Removing the first item with pop(0) shifts every other element, so it takes time proportional to the length. Doing that in a loop over a large queue makes the loop quadratic.
A deque (pronounced "deck", short for double-ended queue) is optimized for adding and removing at either end, in constant time.
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print(d) # deque([0, 1, 2, 3, 4])
print(d.popleft()) # 0
print(d.pop()) # 4
d.rotate(1) # move items one step to the right
print(d) # deque([3, 1, 2])Bounded history with maxlen
With maxlen, the deque keeps only the newest items. Adding to a full deque silently drops an item from the opposite end. This is a clean way to keep "the last N" of anything.
from collections import deque
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
print(recent) # deque([2, 3, 4], maxlen=3)Breadth-first search
A queue is first in, first out, and a deque makes that cheap. This example also uses a dict for the graph and a set for the visited nodes.
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return order
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs_order(graph, "a")) # ['a', 'b', 'c', 'd']Each collection does the job it is best at. The dict maps nodes to neighbors, the set gives fast "have I been here" checks, and the deque holds the waiting nodes.
Trade-offs
- Indexing in the middle of a deque, such as
d[500], takes time proportional to the distance from the nearer end. A list gives constant-time indexing. If you need random access, keep a list. - Slicing does not work on a deque. Convert with
list(d)first. - For multi-threaded producer and consumer code,
queue.Queueadds locking and blocking. A plain deque does not.
Where frozenset fits
Earlier chapters showed that dict keys and set elements must be hashable. A set is not hashable, so you cannot put one inside another set or use it as a dict key. A frozenset is the immutable version, and it is hashable as long as its elements are.
route_costs = {
frozenset({"A", "B"}): 7,
frozenset({"B", "C"}): 4,
}
# Order of the pair does not matter for a frozenset key
print(route_costs[frozenset({"B", "A"})]) # 7Use a frozenset key when the identity of a pair or group does not depend on order. If order matters, use a tuple key instead.
Choosing among the specialized types
| Situation | Reach for | Instead of |
|---|---|---|
| Fixed record with named fields | `namedtuple` or `NamedTuple` | A bare tuple read by index |
| Count how often items occur | `Counter` | `dict` with `.get(k, 0) + 1` |
| Group items under keys | `defaultdict(list)` or `defaultdict(set)` | `dict` with `if key not in d` checks |
| Queue, or the last N items | `deque` | `list` with `pop(0)` or manual trimming |
| Unordered group used as a key | `frozenset` | `set`, which is unhashable |
All of these are subclasses or close relatives of the types you already know. A Counter and a defaultdict are dicts, so in, .items(), and iteration all work. A namedtuple is a tuple. Everything you learned about hashability and mutability still applies.
Common errors
- Expecting
Counter.updateto replace values. It adds. Build a newCounterif you want to start over. - Reading a
defaultdictto test for a key. The read inserts the key. Useinor.get(). - Using
dequefor random access. Middle indexing is slow. Use a list. - Calling the factory.
defaultdict(list())fails. Passlist. - Treating a namedtuple as fully immutable. If a field holds a list, you can still change that list.
- Assuming
a - bon Counters keeps negatives. It drops them.
Exercises
Exercise
You run d = defaultdict(list) and then if d["cat"]: print("found"). The key "cat" was never added. What does d contain afterward, and how would you rewrite the check so it does not change d?
Show answer
After the read, d contains {"cat": []}, because indexing a missing key calls the factory and stores the result. Rewrite the check as if d.get("cat"): print("found"), or if "cat" in d and d["cat"]:. Neither one inserts a key.
Exercise
Given a = Counter("aabbc") and b = Counter("abbd"), what is dict(a - b), and how could you get the difference with negative counts kept?
Show answer
dict(a - b) is {'a': 1, 'c': 1}, because the - operator drops results that are zero or negative. To keep negatives, copy the first counter and call subtract: r = Counter(a); r.subtract(b). That gives a: 1, b: 0, c: 1, d: -1.
Exercise
A program keeps a log of the 100 most recent events. New events arrive constantly, and old ones must be discarded automatically. 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, and once the deque holds 100 items, the oldest item on the left is dropped automatically.