Sub topic 9
Choosing between dict, Counter, defaultdict, list, and deque
This chapter assumes you have read the earlier chapters on Counter, defaultdict, and deque. It also assumes you are comfortable with dict and list. Here you will turn that knowledge into a decision: given a task, which container should you reach for?
Start from the question the data answers
Each container is best at one kind of question. Ask what you need to do with the data, then match it to the structure.
| Need | Best fit | Why |
|---|---|---|
| Look up a value by a known key | `dict` | Direct key-to-value mapping, with no extras to surprise you |
| Count how often each item occurs | `Counter` | Tallies an iterable and offers `most_common` and arithmetic |
| Group or accumulate values per key | `defaultdict` | Creates the starting value on first access |
| Keep an ordered sequence you index into | `list` | Fast access by position and fast append at the end |
| Add and remove at both ends | `deque` | Fast `append`, `appendleft`, `pop`, and `popleft` |
| Keep only the last N items | `deque(maxlen=N)` | Drops the oldest item automatically |
A decision flow
The diagram below follows the same logic as the table. Start at the top and answer each question in turn.
A worked example
Suppose you have a stream of events, each a (user, action) pair. Three different questions about the same data call for three different containers.
from collections import Counter, defaultdict, deque
events = [
("alice", "login"),
("bob", "login"),
("alice", "upload"),
("alice", "logout"),
("bob", "upload"),
("bob", "upload"),
]
# Which action is most common? Counting, so Counter.
action_counts = Counter(action for _, action in events)
# What did each user do? Grouping, so defaultdict(list).
actions_by_user = defaultdict(list)
for user, action in events:
actions_by_user[user].append(action)
# What were the last three events? Recent items, so a bounded deque.
recent = deque(maxlen=3)
for event in events:
recent.append(event)
print(action_counts.most_common(1)) # [('upload', 3)]
print(dict(actions_by_user))
# {'alice': ['login', 'upload', 'logout'], 'bob': ['login', 'upload', 'upload']}
print(list(recent))
# [('alice', 'logout'), ('bob', 'upload'), ('bob', 'upload')]You could write all three with a plain dict and list, but each version would need extra code. These are the extras:
- A check for whether a key exists.
- A manual
+= 1. - A slice or a
pop(0)to trim old items.
The specialized containers move that code into the type.
When plain dict or list is the better choice
The specialized types are not upgrades. They add behavior, and unwanted behavior costs you.
- Use
dictwhen a missing key is a bug. A plaindictraisesKeyErroron a missing key, which exposes typos. Adefaultdicthides them by silently inserting a new entry. - Use
listwhen you index by position. Readingitems[500]in alisttakes constant time. In adeque, indexing near the middle is slower, because the deque is built from linked blocks rather than one contiguous array. - Use
listfor append-and-iterate work. If you only add to the end and loop over the result,listdoes everything you need. - Use
Counteronly when values are counts. If the values are prices, names, or lists,Counteroffers nothing and its arithmetic would mislead readers.
Common mistakes
- Reading a
defaultdictto test for a key. Indexing a missing key inserts it. Usekey in dord.get(key)when you only want to check. - Using
list.pop(0)as a queue. Removing the first item shifts every other item, so the cost grows with the list length.deque.popleft()takes constant time. - Expecting
Countersubtraction to keep negatives. The-operator drops results at or below zero. If you need negative counts, use thesubtractmethod, which keeps them. - Counting unhashable items.
Counteranddictkeys must be hashable. Convert a list to a tuple before counting it. - Forgetting that
maxlendiscards silently. A full bounded deque drops the opposite end with no warning. That suits a "last N items" window and is a hazard when you must keep everything.
Quick rules of thumb
- If you wrote
if key not in d: d[key] = ...just before updating, considerdefaultdict. - If you wrote
d[key] = d.get(key, 0) + 1, useCounter. - If you wrote
items.pop(0)oritems.insert(0, x), usedeque. - If you wrote
items = items[-n:]after every append, usedeque(maxlen=n). - If none of those patterns appear, start with
dictorlist. You can switch later without changing much code, because the specialized types share the same interfaces asdictandlist.
Exercise
You are processing a log file line by line. You need (1) the number of times each HTTP status code appears, (2) a list of URLs for each status code, and (3) the most recent 5 lines for an error report. Which container fits each need?
Show answer
(1) Counter, because you are tallying hashable status codes and can call most_common. (2) defaultdict(list), because you group URLs per status code and the list is created on first access. (3) deque(maxlen=5), because it keeps only the latest five lines and discards older ones automatically.
Exercise
A teammate writes queue = [] and takes work with queue.pop(0) in a loop over 1,000,000 jobs. What is the problem, and what is the fix?
Show answer
Each pop(0) shifts all remaining items, so the total cost grows quadratically with the number of jobs. Replace the list with collections.deque and use popleft(), which takes constant time.