Module 15 · Python Standard Libraries — topic 10 of 13
collections
Specialised containers: Counter for counting, defaultdict for automatic defaults, deque for fast queues, namedtuple for lightweight records, OrderedDict for ordering tricks, and ChainMap for layered lookups.
Learning objectives
- Count items with Counter
- Group data with defaultdict and queue it with deque
- Use namedtuple, OrderedDict and ChainMap appropriately
Definition
collections provides container types that extend list, dict and tuple with specialised behaviour: counting (Counter), default values (defaultdict), double-ended queues (deque), named fields (namedtuple), order operations (OrderedDict) and combined mappings (ChainMap).
Introduction
Counting words, grouping records, keeping the last N items, building caches — collections has a ready-made type for each.
Why it matters
The right container removes boilerplate and often makes code faster: deque appends and pops at both ends in constant time, unlike list.
Detailed explanation
Counter(iterable) counts items; most_common(n) returns the top n; counters can be added and subtracted; missing keys count as 0.
defaultdict(list) creates a missing key's value automatically by calling the factory (list, int, set...), perfect for grouping.
deque supports fast append/appendleft and pop/popleft; maxlen keeps only the most recent items.
namedtuple("Point", "x y") creates a tuple subclass with named fields, _replace and _asdict. For mutable records, dataclasses are often better.
OrderedDict offers move_to_end and popitem(last=False), useful for LRU caches (ordinary dicts already keep insertion order).
ChainMap(dict1, dict2) searches several mappings in order, ideal for layered settings such as user overrides on top of defaults.
All these types work with normal Python syntax — len(), in, iteration and indexing where it makes sense — so they can usually replace a list or dict without changing the surrounding code.
Syntax
- Counter counts.
- defaultdict groups.
- deque queues.
Code examples
Counting
[('i', 4), ('s', 4)] 4 0
Counter({'a': 4, 'c': 2, 'b': 1})Grouping and queues
{'A': ['B', 'C'], 'B': ['D']}
deque([0, 2, 3], maxlen=3)More examples
Records, an LRU cache and layered settings
3 Point(x=3, y=10) {'x': 3, 'y': 4}
['a', 'c']
dark enStep-by-step explanation
- _replace returns a new namedtuple because tuples are immutable.
- Reading 'a' marks it as recently used, so adding 'c' evicts 'b', the least recently used key.
- ChainMap finds theme in the user layer and lang in the defaults layer.
Expected output
Running “Records, an LRU cache and layered settings” prints exactly:
Practical applications
- Word frequencies and vote tallies with Counter.
- Breadth-first search queues with deque.
Best practices
- Use Counter instead of manual counting dictionaries.
- Use deque for queues.
- Prefer dataclasses for mutable records.
Common mistakes
list.pop(0) as a queue
Avoid
Prefer
Removing from the front of a list shifts every element.
Important notes
- dict and list subclasses UserDict and UserList are also in collections, for customising behaviour.
Key takeaways
- Counter, defaultdict and deque solve common tasks.
- namedtuple gives tuples named fields.
- OrderedDict and ChainMap handle ordering and layering.
Try it yourself
- 1Use Counter to find the three most common letters in a sentence.
- 2Keep the last five commands typed by a user with a deque.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
3 questions test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?
- ModerateWhat is printed?