Counter, defaultdict and deque
Counting things, grouping things and keeping the last few things are the three loops data engineers write most. The collections module has a ready-made container for each, shorter and faster than writing them by hand. This lesson shows Counter, defaultdict and deque, and the traps in each.
Foundations · Python for data engineers · Bronze · Built-in data structures, lesson 3 of 3
On this page
Read first: Lists, dicts and sets: what each operation costs (skip if you know it)
In plain words first
Counter: a tally sheet
defaultdict: labelled boxes that appear by themselves
deque: a short shelf
The standard library's data structures
collections adds a few containers that remove boilerplate from the loops data engineers write every day: counting, grouping and keeping the last few items. They are written in C, so they are also faster than the hand-rolled versions.
Counter: counting in one line
Counter is a dict from item to count. Build it from any iterableiterable: Anything you can loop over with for: a list, a string, a dict, a range, a file. Calling iter() on it gives a fresh iterator. Learn more →, read a missing key as 0, and add counters together. most_common(n) gives the top n, but ties come out in first-seen order, not alphabetically; sort yourself when the tie order matters.
from collections import Counter dishes = ["dosa", "chai", "idli", "chai", "dosa", "vada"] counts = Counter(dishes) print("chai:", counts["chai"], "pizza:", counts["pizza"]) # a missing dish counts as 0 print(counts.most_common(2)) # tie: dosa came first in the list # Highest count first; for equal counts, A to Z. # The key -count turns 2 into -2, so bigger counts sort earlier. by_count_then_name = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0])) print(by_count_then_name[:2])
Output from a real run
chai: 2 pizza: 0
[('dosa', 2), ('chai', 2)]
[('chai', 2), ('dosa', 2)]+ keeps only items whose total is above zero: Counter(chai=1) + Counter(chai=-1) gives an empty Counter(), so chai disappears. To keep zeros and negatives, add into the counter you already have: counts.update(more_dishes) adds each count from more_dishes into counts and removes nothing.defaultdict: grouping without the "first time?" check
defaultdict(list) calls list() to create a value the first time a missing key is used, so grouping becomes one line per item. The same works with int for counters and set for unique members.
from collections import defaultdict orders = [("o1", "spice-hub"), ("o2", "tiffin-co"), ("o3", "spice-hub")] by_restaurant = defaultdict(list) for order_id, restaurant in orders: by_restaurant[restaurant].append(order_id) print(dict(by_restaurant)) print(by_restaurant["closed-place"]) print("closed-place" in by_restaurant)
Output from a real run
{'spice-hub': ['o1', 'o3'], 'tiffin-co': ['o2']}
[]
TrueLook at the last two lines: reading a missing key also creates it. Handing a defaultdict to other code means typos silently return empty groups and grow the dict. Convert with dict(...) before returning it.
deque: both ends, and a bounded window
A deque (double-ended queue) appends and pops at both ends in O(1); a list is O(n) at the front. With maxlen it becomes a ring buffer that keeps only the newest items, which is how "the last N" and sliding windowssliding window: Keeping a running total or set over the last k items and updating it as you move one item forward, instead of recomputing from scratch. Learn more → are kept in O(n) memory.
from collections import deque queue = deque(["o1", "o2"]) queue.append("o3") served = queue.popleft() # take from the front print("served:", served, "| still waiting:", list(queue)) recent = deque(maxlen=3) for eta in [30, 25, 40, 35, 20]: recent.append(eta) print("last three ETAs:", list(recent))
Output from a real run
served: o1 | still waiting: ['o2', 'o3'] last three ETAs: [40, 35, 20]
OrderedDict: an order you can rearrange
A plain dict remembers the order keys were first added, but that order is fixed: giving an existing key a new value does not move it. OrderedDict adds two O(1) moves a plain dict does not have: move_to_end(key) sends a key to the back, and popitem(last=False) removes the key at the front. Together they keep "most recently used last, oldest first", which is what a cache needs when it is full and must forget something.
from collections import OrderedDict plain = {"spice-hub": 1, "tiffin-co": 1} plain["spice-hub"] = 2 print("plain dict keeps the old position:", list(plain)) viewed = OrderedDict() for place in ["spice-hub", "tiffin-co", "dosa-den", "spice-hub", "chai-point"]: viewed[place] = True viewed.move_to_end(place) # looked at again: now the newest if len(viewed) > 3: oldest, _ = viewed.popitem(last=False) # drop from the front print("forgot:", oldest) print("oldest to newest:", list(viewed))
Output from a real run
plain dict keeps the old position: ['spice-hub', 'tiffin-co'] forgot: tiffin-co oldest to newest: ['dosa-den', 'spice-hub', 'chai-point']
Follow spice-hub: it was first, but looking at it again moved it behind dosa-den, so when the fourth place arrived, tiffin-co was the oldest and was dropped. A plain dict would need O(n) work to do the same reshuffle.
| Question | Reach for |
|---|---|
| How many of each? | Counter |
| Which items belong to each key? | defaultdict(list), then dict() |
| First in, first out | deque with append / popleft |
| The last N items of a stream | deque(maxlen=N) |
| Most recently used last, drop the oldest | OrderedDict with move_to_end / popitem(last=False) |
Common mistakes
- Trusting most_common for ties — It keeps first-seen order. Sort by (-count, key) for a deterministic answer.
- Returning a defaultdict — Lookups of missing keys silently create entries. Return dict(d).
- Using list.pop(0) as a queue — O(n) per pop. Use deque.popleft().
- Expecting d[key] = value to move a key in a plain dict — Updating keeps the original position. Use OrderedDict.move_to_end, or delete and re-insert the key.
Key takeaways
- Counter counts; most_common breaks ties by first appearance.
- Counter + Counter drops totals that are not positive.
- defaultdict groups in one line; convert it to dict before handing it out.
- deque is O(1) at both ends; maxlen keeps only the newest items.
- OrderedDict moves a key to the end and drops the oldest in O(1).
Interview prep
THE QUESTION
"When would you use a defaultdict instead of a normal dict?"
Avoid: "most_common gives the top items sorted by count and then by name". Ties come out in first-seen order.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between Counter(a) + Counter(b) and c.update(b)?"
Scenario"Keep the last 1,000 latency readings of a service and report their average every minute."
Trap"Reading a missing key from a defaultdict is harmless."
Check yourself
4 questionsCounter("aab")["z"] returns...
Show the answer
0. Missing keys count as zero.
d = defaultdict(list); d["x"] — what happens to d?
Show the answer
It now has key "x" with []. Reading a missing key creates it with the default.
The best structure to keep the last 100 events of an endless stream?
Show the answer
deque(maxlen=100). It drops the oldest item automatically and stays at 100 items.
d = {"a": 1, "b": 2}; d["a"] = 9; list(d) is...
Show the answer
["a", "b"]. A plain dict keeps the first-insertion position when a value is updated. OrderedDict.move_to_end is how you move a key.
Practise this
Problems that use this, graded on hidden tests
- Top K Frequent WordsCore Python & data structures Easy
- Group Records by KeyCore Python & data structures Easy
- Keep the Last N EventsCore Python & data structures Medium
Keep going
Up next · new module: Everyday idioms · 5 min readSorting with key functions
Tuple keys, mixed directions, stability and data with None in it.
Related lessons
Previous: Comprehensions
Primary sources: collections