Reading history

Python collections Module: Counter, defaultdict, deque, namedtuple

5 min read 2 views

Learn the Python collections module: Counter and most_common, defaultdict for grouping, deque for queues, namedtuple records and OrderedDict.

Lists, dictionaries, tuples and sets cover most needs, but some tasks come up so often that the standard library includes specialised containers for them. The collections module provides Counter for counting, defaultdict for grouping, deque for fast queues, namedtuple for readable records and OrderedDict for order-aware dictionaries. Each one replaces several lines of hand-written code with one clear line.

In this lesson you will learn

  • Counting items with Counter and most_common
  • Grouping and totalling with defaultdict
  • Queues and fixed-size history with deque
  • Named fields with namedtuple
  • Reordering keys with OrderedDict

Counter and defaultdict

from collections import Counter, defaultdict

text = "the cat and the dog and the bird"
counts = Counter(text.split())
print(counts)
print(counts["the"], counts["fish"])        # missing keys give 0
print(counts.most_common(2))

votes = Counter(["A", "B", "A", "C", "A", "B"])
votes.update(["C", "C"])
print(votes)

groups = defaultdict(list)                   # missing keys start as []
for name, dept in [("Nusrat", "CSE"), ("Arif", "EEE"), ("Tania", "CSE")]:
    groups[dept].append(name)
print(dict(groups))

totals = defaultdict(int)                    # missing keys start as 0
for item, qty in [("pen", 3), ("book", 1), ("pen", 2)]:
    totals[item] += qty
print(dict(totals))

Output

Counter({'the': 3, 'and': 2, 'cat': 1, 'dog': 1, 'bird': 1})
3 0
[('the', 3), ('and', 2)]
Counter({'A': 3, 'C': 3, 'B': 2})
{'CSE': ['Nusrat', 'Tania'], 'EEE': ['Arif']}
{'pen': 5, 'book': 1}
  • Counter(iterable) counts how many times each item appears. It is a dictionary subclass, so counts["the"] works, and a missing item returns 0 instead of raising KeyError.
  • most_common(n) returns the n most frequent items, which is the classic “top words” or “most popular product” query.
  • update() adds more counts. Counters also support + and - between them.
  • defaultdict(list) creates an empty list automatically the first time a key is used, so grouping needs no if key not in d check. defaultdict(int) starts missing keys at 0 for totals.
  • Wrapping with dict() prints a normal dictionary.

deque, namedtuple and OrderedDict

from collections import deque, namedtuple, OrderedDict

queue = deque(["Nadia", "Rafi"])
queue.append("Mitu")          # join at the back
queue.appendleft("VIP")       # jump to the front
print(queue.popleft(), queue.popleft(), list(queue))

recent = deque(maxlen=3)      # keeps only the last 3 items
for page in ["home", "about", "blog", "contact", "shop"]:
    recent.append(page)
print(list(recent))

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p, p.x, p[1])
x, y = p
print(x + y, p._asdict())

cache = OrderedDict()
for k in ["a", "b", "c"]:
    cache[k] = k.upper()
cache.move_to_end("a")        # mark "a" as most recently used
cache.popitem(last=False)     # remove the oldest item
print(list(cache.keys()))

Output

VIP Nadia ['Rafi', 'Mitu']
['blog', 'contact', 'shop']
Point(x=3, y=4) 3 4
7 {'x': 3, 'y': 4}
['c', 'a']
  • A deque (“deck”, double-ended queue) adds and removes items at both ends in constant time. list.pop(0) has to shift every remaining element, so a deque is the right tool for a queue. See Queue Data Structure for the concept.
  • deque(maxlen=3) automatically drops the oldest item when full, perfect for “recent history” features.
  • namedtuple("Point", ["x", "y"]) creates a tuple type whose fields have names. It stays immutable, can be unpacked and indexed like a tuple, and prints readably. For records with methods or defaults, a dataclass is often better.
  • Normal dictionaries keep insertion order since Python 3.7. OrderedDict is still useful for its move_to_end and popitem(last=False) methods, the basis of a least-recently-used (LRU) cache.

Which Container for Which Job?

NeedUseInstead of
Count occurrencesCounterA dict with get(k, 0) + 1
Group items by keydefaultdict(list)setdefault or if-checks
Queue (FIFO) or both endsdequelist.pop(0)
Last N itemsdeque(maxlen=N)Slicing a list repeatedly
Lightweight immutable recordnamedtupleA plain tuple with magic indexes

Common Mistakes

  1. Using list.pop(0) for queues on large data; use deque.popleft().
  2. Forgetting the factory is a function: write defaultdict(list), not defaultdict([]).
  3. Reading a missing key from a defaultdict just to check it, which silently adds that key; use in to test.
  4. Trying to change a namedtuple field; use p._replace(x=10) to get a modified copy.

Practice Exercises

Exercise 1. Find the most common letter in "mississippi".

Show answer
from collections import Counter
print(Counter("mississippi").most_common(1))   # [('i', 4)]

“i” and “s” both appear 4 times; on a tie, most_common keeps the order the items were first seen.

Exercise 2. Group the words ["apple", "avocado", "banana", "blueberry", "cherry"] by their first letter.

Show answer
from collections import defaultdict
groups = defaultdict(list)
for w in ["apple", "avocado", "banana", "blueberry", "cherry"]:
    groups[w[0]].append(w)
print(dict(groups))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

Frequently Asked Questions

Is a deque faster than a list?

For adding or removing at the front, yes: O(1) instead of O(n). For random access by index in the middle, a list is faster.

Do I need to install the collections module?

No. It is part of Python’s standard library; just import what you need, for example from collections import Counter.

Summary

  • Counter counts and ranks items.
  • defaultdict removes “key missing” checks when grouping or totalling.
  • deque is a fast queue and, with maxlen, a rolling history.
  • namedtuple gives tuples readable field names.

Next: Python math, random and statistics.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *