Skip to content
Bronze 6 min read · Data structures 3 practice problems ↓

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

Read first: Lists, dicts and sets: what each operation costs (skip if you know it)

In plain words first

Counter: a tally sheet

Every time you see a word, add a mark next to it. At the end, read off the most common ones.

defaultdict: labelled boxes that appear by themselves

Drop a receipt into the box for its city; if there is no box yet, one appears.

deque: a short shelf

Add at one end, take from either end, and when the shelf is full the oldest item falls off the other side.

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.

Python · counting dishes, and the tie order
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)]
Adding counters with + drops zero and negative counts: Adding two counters with + 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.

Python · orders grouped by restaurant
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']}
[]
True

Look 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.

Python · a queue, and the last three ETAs
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.

Python · the last three restaurants a customer looked at
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.

QuestionReach for
How many of each?Counter
Which items belong to each key?defaultdict(list), then dict()
First in, first outdeque with append / popleft
The last N items of a streamdeque(maxlen=N)
Most recently used last, drop the oldestOrderedDict 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?"

When I am grouping or counting and every new key needs the same starting value: defaultdict(list) for groups, defaultdict(int) for counts. It removes the "is this the first time I see the key?" branch. I am careful at the boundary though: reading a missing key inserts it, so I convert to a plain dict before returning the result, and I use Counter when the job is only counting.

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)?"
Both add counts, but + keeps only keys whose total is positive, so zeros and negatives vanish; update adds in place and keeps every key.
Scenario"Keep the last 1,000 latency readings of a service and report their average every minute."
A deque(maxlen=1000): appending drops the oldest reading automatically, memory stays fixed, and averaging 1,000 numbers each minute is trivial. For a per-event moving average, I would also keep a running sum.
Trap"Reading a missing key from a defaultdict is harmless."
It inserts the key with a default value. Code that only meant to check a key grows the dict and makes later membership tests true. Use .get() or `in`, and return dict(d) to callers.

Check yourself

4 questions

Counter("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

See all 5 problems →

Keep going

Up next · new module: Everyday idioms · 5 min read
Sorting with key functions
Tuple keys, mixed directions, stability and data with None in it.

Related lessons

Previous: Comprehensions

Primary sources: collections