Skip to content

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.

Beginner 10 min read·Lesson 231 of 306 in Python Programming

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

Python
from collections import Counter, defaultdict, deque, namedtuple
Counter(words).most_common(3)
groups = defaultdict(list)
recent = deque(maxlen=5)
Point = namedtuple("Point", "x y")
  • Counter counts.
  • defaultdict groups.
  • deque queues.

Code examples

Counting

Python
from collections import Counter
c = Counter("mississippi")
print(c.most_common(2), c["s"], c["z"])
print(Counter(a=3, b=1) + Counter(a=1, c=2))
Output
[('i', 4), ('s', 4)] 4 0
Counter({'a': 4, 'c': 2, 'b': 1})

Grouping and queues

Python
from collections import defaultdict, deque
graph = defaultdict(list)
for a, b in [("A", "B"), ("A", "C"), ("B", "D")]:
graph[a].append(b)
print(dict(graph))
q = deque([1, 2, 3], maxlen=3)
q.append(4)
q.appendleft(0)
print(q)
Output
{'A': ['B', 'C'], 'B': ['D']}
deque([0, 2, 3], maxlen=3)

More examples

Records, an LRU cache and layered settings

Python
from collections import ChainMap, OrderedDict, namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p._replace(y=10), p._asdict())
class LRU:
def __init__(self, size):
self.size = size
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return None
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.size:
self.data.popitem(last=False)
cache = LRU(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a")
cache.put("c", 3)
print(list(cache.data))
settings = ChainMap({"theme": "dark"}, {"theme": "light", "lang": "en"})
print(settings["theme"], settings["lang"])
Output
3 Point(x=3, y=10) {'x': 3, 'y': 4}
['a', 'c']
dark en

Step-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:

TextOutput
3 Point(x=3, y=10) {'x': 3, 'y': 4}
['a', 'c']
dark en

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

queue = []
queue.pop(0) # slow for long lists

Prefer

queue = deque()
queue.popleft()

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

  1. 1
    Use Counter to find the three most common letters in a sentence.
  2. 2
    Keep 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?
Practise this topic