Beyond dict and list: namedtuple, deque, and ChainMap
Python's built-in containers cover an enormous range, and most code needs nothing else.
But a few recurring shapes â a fixed record you want to index by name and unpack by
position, a queue that must grow at both ends, a stack of configuration layers where the
first hit wins â are solved once and for all by the collections module. Reaching for a
hand-rolled list-plus-dict in those situations produces code that is slower, harder to
read, and subtly wrong at the edges: off-by-one pops, accidental aliasing of default
values, and config merging that mutates the caller's dictionary.
This lesson walks the four types that pay for themselves fastest â namedtuple,
deque, ChainMap, and Counter/defaultdict â and closes with a decision table for
picking a container by the operation you perform most often.
Records you can unpack, index, and compare
A tuple with magic indexes (row[2]) is unreadable and fragile; a full class for a plain
record is verbose and noisy. namedtuple sits between: it generates a class with named
fields that still behaves like a tuple â hashable, unpackable, comparable â with no
runtime ceremony.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
Reading = namedtuple("Reading", ["sensor", "value", "unit"], defaults=["unknown"])
p = Point(3, 4)
print(p.x, p[1]) # 3 4 â name and position both work
sx, sy = p # unpacking still works
print(p._asdict()) # {'x': 3, 'y': 4}
r = Reading("a1", 21.5) # unit falls back to the default
print(r._replace(value=22.0)) # Reading(sensor='a1', value=22.0, unit='unknown')
Two details separate productive use from cargo-culting. defaults applies from the right,
so partial defaults are expressed as a trailing list, not a dict. And _replace returns a
new instance â the immutability you bought with the tuple base class is not given up
quietly, which makes these safe to share across threads and use as dictionary keys.
| Need | Use | Because |
|---|---|---|
| Immutable record, tuple semantics | collections.namedtuple | Zero dependencies, fast |
| Type-hinted fields, methods, defaults | typing.NamedTuple | Annotate fields instead of a string spec |
| Mutable record with validation | @dataclass | Assignments and __post_init__ allowed |
| Mutable record, validation, serialisation | pydantic.BaseModel | Boundary data with real checking |
| C-level speed for hot loops | __slots__ class | Fixed attributes, no per-instance dict |
If you find yourself typing the same string spec in five places, or needing type hints
that match the fields, migrate to typing.NamedTuple â the syntax is identical in spirit
and static checkers can then catch a swapped argument.
deque: O(1) at both ends
A Python list is a dynamic array: append and indexing are cheap, but insert(0, ...) and
pop(0) shift every remaining element. deque (double-ended queue) is the opposite
trade â constant-time appends and pops at both ends, at the cost of slower indexed access
in the middle. Any time your access pattern is "front and back", a list is the wrong tool
and the slowdown appears exactly when the collection grows.
from collections import deque
recent = deque(maxlen=5) # bounded: oldest evicted automatically
for n in range(1, 9):
recent.append(n)
print(recent) # deque([4, 5, 6, 7, 8], maxlen=5)
recent.appendleft(0)
print(recent.popleft()) # 0
seen = deque(maxlen=1000)
def already_processed(key: str) -> bool:
hit = key in seen # O(n) in the window, n capped at 1000
seen.append(key)
return hit
The maxlen argument is the feature most people miss: a bounded deque is a complete
sliding-window implementation with eviction handled for you, which makes it ideal for
recent-item caches, rate-limit counters, and "last N errors" buffers. Rotation is another
deque specialty â dq.rotate(n) moves entries around a ring in O(k), useful for round-robin
scheduling without index arithmetic.
ChainMap for layered configuration
Configuration is naturally layered: process defaults, then a config file, then environment
variables, then per-invocation overrides. Merging those into one dict too early means you
cannot tell which layer supplied a value, and mutating the merged dict can leak changes
back into the originals. ChainMap holds the layers separately and looks them up in
order, so the first mapping that contains a key wins while later ones remain intact.
from collections import ChainMap
import os
defaults = {"timeout": 30, "retries": 3, "verbose": False}
file_cfg = {"timeout": 10, "retries": 5}
env_cfg = {
k[4:].lower(): v
for k, v in os.environ.items()
if k.upper().startswith("APP_") and k[4:].lower() in defaults
}
settings = ChainMap(env_cfg, file_cfg, defaults)
print(settings["timeout"]) # 10 â from file_cfg
settings["verbose"] = True # writes to the FIRST map only
print(env_cfg["verbose"]) # True
print(file_cfg.get("verbose")) # None â untouched
Writes landing in the first map is the behaviour to remember: ChainMap never merges
downward, so an override stays an override and the file-derived values you loaded at
startup are not silently rewritten. When you do want a flattened snapshot â for logging
or for handing to a library that expects a plain dict â call settings.maps and merge
explicitly, in a direction you choose.
Counter, defaultdict, and the end of setdefault
Two more collections types remove the same class of boilerplate. Counter is a dict
subclass for counting hashables, with arithmetic (+, -), most_common, and
constructors that take any iterable. defaultdict supplies a factory for missing keys,
eliminating the if key not in d: d[key] = [] preamble that appears in nearly every
grouping loop ever written.
from collections import Counter, defaultdict
words = "the quick brown fox jumps over the lazy dog the fox".split()
print(Counter(words).most_common(3)) # [('the', 3), ('quick', 1), ('brown', 1)]
print(Counter(w[-1] for w in words)) # Counter of word endings
by_letter = defaultdict(list)
for w in words:
by_letter[w[0]].append(w)
print(dict(by_letter))
counts = Counter({"apples": 4, "pears": 2})
counts.update(["apples", "apples", "bananas"])
print(counts - Counter({"apples": 5})) # arithmetic on counts
defaultdict(list) is the idiomatic grouping idiom, but its factory is called
automatically â including inside membership tests you did not intend to write. Checking
by_letter["z"] with the in operator first does not create an entry, but reading the
value does; if you need a read that must not mutate, use a plain dict with .get(), or
Counter where the domain is counts.
Subclassing the standard containers safely
Sometimes the built-in behaviour is right except for one detail â a list that rejects
duplicates, a dict that rejects unknown keys, a counter that only accepts positive
increments. The collections module ships UserList, UserDict, and UserString
explicitly for this: they behave like their built-in counterparts but store contents in
an instance attribute, so overriding a method does not fight the C implementation.
from collections import UserDict
class Config(UserDict):
def __setitem__(self, key, value):
if not key.isupper():
raise KeyError(f"config keys must be uppercase, got {key!r}")
super().__setitem__(key, value)
cfg = Config()
cfg["TIMEOUT"] = 30
try:
cfg["timeout"] = 10
except KeyError as exc:
print(exc) # config keys must be uppercase, got 'timeout'
The important subtlety is that subclassing the built-in dict directly can skip your
overridden methods on some internal code paths, because the interpreter optimises the
built-in type's own operations. UserDict routes everything through Python-level
methods, so an override is always honoured â which is exactly what you want when the
override encodes a validation rule.
Choosing by operation, not by habit
The fastest container is the one whose hot path matches your access pattern. Before reaching for a list out of habit, ask what operation dominates.
| Dominant operation | Container | Complexity |
|---|---|---|
| Append, index by position | list | Amortised O(1) append, O(1) index |
| Append/pop at both ends | deque | O(1) front and back |
| Key lookup, frequent iteration | dict | O(1) average lookup |
| Uniqueness, membership tests | set | O(1) average membership |
| Counts of hashables | Counter | O(1) per increment |
| Grouping rows by a key | defaultdict(list) | O(1) per append |
| Layered key resolution | ChainMap | O(layers) per lookup |
| Fixed record, positional use | namedtuple | Tuple speed, named access |
Two rules of thumb close the gap between this table and real code. First, measure before optimising the container choice â the difference between a list and a deque only matters once the collection is large and the pattern is hot. Second, prefer the container that makes the invariant obvious: a bounded deque documents "only the last thousand matter" in its constructor, which says more than a comment ever will.
Common Mistakes
Using pop(0) on a list as a queue inside a loop
Fix: Use collections.deque with popleft() so removal stays constant time
Building defaults with defaultdict inside membership checks
Fix: Use plain dict.get for reads that must not create entries
Merging configuration layers into one dict at startup
Fix: Keep them in a ChainMap so provenance survives and writes hit the override layer only
Indexing namedtuples by position after adding a field
Fix: Switch to typing.NamedTuple with named reads so field order stops mattering
Forgetting maxlen when tracking recent items
Fix: Pass maxlen to deque and let eviction happen automatically
Best Practices
- Pick the container whose dominant operation matches your hot loop
- Give namedtuple fields meaningful names and prefer _replace over manual rebuilding
- Use Counter for any tallying task instead of hand-written increment dicts
- Keep configuration layers separate until the moment you need a flat snapshot
- Document invariants like window size in the constructor rather than in a comment
Key Takeaways
- namedtuple gives named, hashable, unpackable records with no class boilerplate
- deque is O(1) at both ends and supports bounded windows via maxlen
- ChainMap resolves keys through ordered layers and writes only to the first
- Counter and defaultdict remove counting and grouping boilerplate entirely
- Choose containers by the operation you perform most, not by familiarity