Sub topic 9
Choosing between dict, Counter, defaultdict, list, and deque
The earlier chapters covered each container on its own. This chapter helps you pick one for a given task and avoid the mistakes that come from picking the wrong one.
It assumes you can write basic Python loops and functions, use dict and list (key lookup, append), and know why a list can't be a dict key (unhashable objects). You should also be able to import names from the standard library. You should have read the earlier chapters on Counter, defaultdict, and deque, so this chapter reviews them quickly.
Start from the operation, not the type
Containers are tools for operations. Before choosing, write down the operations your code performs most often:
- Do you look values up by key, or by position?
- Do you tally how often things occur?
- Do you build a value per key, such as a list or a running total?
- Do you add or remove items at the ends, and at which end?
- Do you need to forget old items automatically?
The table below maps common needs to a first choice.
| Need | First choice | Why |
|---|---|---|
| Map keys to arbitrary values, all set explicitly | `dict` | Simplest, no surprises |
| Count occurrences of hashable items | `Counter` | Missing items read as 0, has `most_common` and arithmetic |
| Group items by key, or accumulate per key | `defaultdict` | Creates the starting value on first access |
| Ordered sequence with indexing and slicing | `list` | Fast index access, fast append and pop at the end |
| Queue (first in, first out) or work at both ends | `deque` | Fast at both ends |
| Keep only the last N items | `deque(maxlen=N)` | Old items drop off automatically |
The diagram turns the same reasoning into a sequence of questions.
No flowchart replaces judgment. The next sections cover the cases where two choices look close.
dict versus Counter
Counter is a subclass of dict. It keeps everything a dict does, including insertion order and key lookup. It adds behavior designed for counting. A plain dict version of word counting needs a branch:
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts) # {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}The Counter version states the intent directly:
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts.most_common(1)) # [('the', 3)]
print(counts["dog"]) # 0, and 'dog' is not addedChoose Counter when:
- The values are tallies of how often a key was seen.
- You want the top N items, or you want to combine tallies with
+,-,&, and|. - You want a missing key to read as 0 without changing the container.
Choose a plain dict when the values are not counts. A mapping from user id to profile object gains nothing from Counter. Its methods such as most_common and elements assume integer values. Storing other types works mechanically, but those methods then fail or give meaningless results.
Counts can reach zero or go negative, for example after subtract. The - operator and the unary + drop entries at or below zero, while subtract keeps them. Pick one convention for your program and stick to it.
from collections import Counter
stock = Counter(apples=3, pears=1)
stock.subtract({"apples": 3, "pears": 2})
print(stock) # Counter({'apples': 0, 'pears': -1})
print(+stock) # Counter()dict versus defaultdict
A defaultdict removes the "does this key exist yet?" step. The factory you pass (such as list, int, or set) creates the starting value the first time a missing key is read.
Grouping with a plain dict has three common forms. The first checks for the key:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for word in words:
if word[0] not in groups:
groups[word[0]] = []
groups[word[0]].append(word)The second uses setdefault:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for word in words:
groups.setdefault(word[0], []).append(word)The third uses defaultdict:
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = defaultdict(list)
for word in words:
groups[word[0]].append(word)
print(dict(groups))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}setdefault and defaultdict both work. They differ in two ways:
setdefault(key, [])builds a new empty list on every call, even when the key exists and the list is thrown away.defaultdict(list)calls the factory only when the key is missing.defaultdictapplies to every lookup, so any code that reads the dictionary can insert keys.setdefaultis explicit at each call site.
That second point is the main reason to choose carefully.
Here is the difference in practice:
from collections import defaultdict
d = defaultdict(int)
d["x"] += 1
print("y" in d) # False
d["y"] # indexing inserts 0
print("y" in d) # True
print(d.get("z")) # None, and get() does not insert 'z'
print(len(d)) # 2Typos become silent bugs. If you write d["totl"] instead of d["total"], a plain dict raises KeyError and tells you immediately. A defaultdict creates a new key and carries on. For data that you build once and then only read, you have two ways to turn off the automatic insertion:
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
frozen = dict(d) # option 1: copy into a plain dict
d.default_factory = None # option 2: missing keys now raise KeyError
try:
d["missing"]
except KeyError as error:
print("KeyError:", error) # KeyError: 'missing'The factory must be callable with no arguments. defaultdict(list()) raises TypeError, because list() is an empty list, not a callable. For a custom default, use a function or lambda, for example defaultdict(lambda: [0, 0]).
A pickling caveat applies as well. A defaultdict that uses a lambda as its factory can't be pickled, because lambdas can't be pickled. A named module-level function or a built-in such as list can be.
defaultdict(int) versus Counter
Both give you a zero for a new key, so they overlap the most. They differ in what a read does:
from collections import Counter, defaultdict
c = Counter()
d = defaultdict(int)
c["a"] # reads 0, does not insert
d["a"] # reads 0, inserts 'a'
print(len(c), len(d)) # 0 1If you only increment, they behave the same. If you also look things up, Counter is safer, and most_common comes with it. Use defaultdict(int) when the values are sums or other numbers that are not tallies of occurrences, such as total sales per region. It also helps when you want the "inserts on read" behavior on purpose, and for factories other than int.
list versus deque
A list and a deque both hold ordered items, but they are built differently. A list stores its items in one contiguous block, so reading items[i] is fast. Adding or removing at the end is also fast. Removing or inserting at the front forces every other item to shift, which takes time proportional to the length.
A deque is built for work at both ends. append, appendleft, pop, and popleft all take constant time. The cost is that reaching the middle takes time proportional to the distance from the nearest end.
| Operation | `list` | `deque` |
|---|---|---|
| `append(x)` / `pop()` (right end) | Fast | Fast |
| `insert(0, x)` / `pop(0)` (left end) | Slow, shifts all items | Fast with `appendleft` / `popleft` |
| `items[i]` near the ends | Fast | Fast |
| `items[i]` in the middle | Fast | Slow |
| Slicing `items[a:b]` | Supported | Not supported, raises `TypeError` |
| Automatic size limit | No | Yes, with `maxlen` |
You can measure the front-removal gap yourself. The exact times vary by machine, but the deque result should be much smaller:
from timeit import timeit
n = 100_000
setup_list = f"q = list(range({n}))"
setup_deque = f"from collections import deque; q = deque(range({n}))"
print("list.pop(0): ", timeit("q.pop(0)", setup=setup_list, number=n // 2))
print("deque.popleft:", timeit("q.popleft()", setup=setup_deque, number=n // 2))Choose deque when:
- You use it as a queue: add on one side, remove from the other.
- You need to limit its size and discard old entries automatically.
- You rotate items, as in a round-robin schedule.
Choose list when:
- You index by position or slice it.
- You sort it, since
list.sort()exists and deque has no sort method. - You only add and remove at the end. A list works fine as a stack (
appendandpop), and a deque gives no advantage there.
A breadth-first search is the classic queue use. The popleft on a deque is what makes it efficient:
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": [],
"E": [],
}
def bfs(start):
seen = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return order
print(bfs("A")) # ['A', 'B', 'C', 'D', 'E']For "the last N items", maxlen removes the need for manual trimming. This moving average keeps at most three values:
from collections import deque
window = deque(maxlen=3)
for value in [10, 20, 30, 40, 50]:
window.append(value)
print(sum(window) / len(window))
# 10.0
# 15.0
# 20.0
# 30.0
# 40.0Two edge cases matter here. First, a full bounded deque discards from the opposite end without raising an error, so data loss is silent. Use maxlen only when forgetting old items is the intent. Second, maxlen is read-only after creation, so you can't resize the same deque. Build a new one with deque(old, maxlen=new_size) instead.
Combining containers
Real programs often use more than one container, and the combinations are common. The next example processes a stream of user events. It counts how often each action happens and keeps the two most recent actions per user.
from collections import Counter, defaultdict, deque
events = [
("ana", "login"),
("bo", "login"),
("ana", "view"),
("ana", "view"),
("bo", "logout"),
("ana", "logout"),
("ana", "view"),
]
recent = defaultdict(lambda: deque(maxlen=2))
actions = Counter()
for user, action in events:
recent[user].append(action)
actions[action] += 1
print(actions.most_common(1))
print({user: list(queue) for user, queue in recent.items()})
# [('view', 3)]
# {'ana': ['logout', 'view'], 'bo': ['login', 'logout']}Each container does one job:
Countertallies the actions. A read never inserts anything.defaultdictcreates a fresh bounded deque the first time a user appears. The factory is alambdabecause each user needs its own deque, anddeque(maxlen=2)needs an argument.deque(maxlen=2)forgets old events without any trimming code.
The list(queue) conversion in the last line has a purpose. A deque prints with its class name and maxlen, and json.dumps can't serialize it. Counter and defaultdict are dict subclasses, so json.dumps handles them. A deque must become a list first.
Common mistakes and how to avoid them
| Mistake | What happens | Fix |
|---|---|---|
| Reading `d[key]` on a `defaultdict` to test for a value | Inserts the key and grows the dict | Use `key in d` or `d.get(key)` |
| Using a `list` as a queue with `pop(0)` | Each removal shifts all items, so the loop slows as the list grows | Use `deque` and `popleft` |
| Slicing a deque, such as `d[1:3]` | `TypeError` | Convert with `list(d)` first, or use `itertools.islice` |
| Indexing into the middle of a large deque in a hot loop | Each access walks from the nearest end | Use a `list` |
| Using `Counter` for non-count values | `most_common` and arithmetic give wrong or failing results | Use a `dict` or `defaultdict` |
| Using `Counter` keys that are lists | `TypeError: unhashable type` | Convert keys to tuples |
| Passing `defaultdict(list())` | `TypeError` | Pass `list`, with no parentheses |
| Expecting `maxlen` to raise when full | Old items vanish silently | Check `len` yourself if loss is not acceptable |
A short checklist
Run through these questions in order.
- Are you counting occurrences of hashable items? Use
Counter. - Are you building a list, set, or sum for each key? Use
defaultdictwithlist,set, orint. - Are the values fixed, set once, or looked up often with possible misses? Use
dict. A missing key should be an error you can see. - Do you need position-based access, slicing, or sorting? Use
list. - Do you remove from the front, or need a size-limited window? Use
deque. - Are you unsure? Start with the plain
dictorlist, and change only when the code shows a clear need, such as a branch inside a loop or a slowpop(0).
Because Counter and defaultdict are dict subclasses, switching between dict and either of them later is usually a small change. Switching between list and deque is also cheap, as long as you don't rely on slicing or middle indexing.
Exercise
You write seen = defaultdict(int) and later check if seen[user] > 0: for each incoming user, to find out whether you have seen them before. After processing 1,000,000 different users, len(seen) is 1,000,000 even though you only meant to record some of them. What went wrong, and what are two ways to fix it?
Show answer
Indexing a missing key in a defaultdict calls int() and stores 0, so the check itself inserts every user it tests. Fix it by testing without inserting: if seen.get(user, 0) > 0: or if user in seen: (when you only add users you want to record). Alternatively, switch to a Counter, whose reads return 0 without inserting.
Exercise
A program keeps a log of the 50 most recent requests as a list. For each new request it runs log.append(req), then if len(log) > 50: log.pop(0). Rewrite the storage so the trimming code is not needed, and say what happens to the oldest entry.
Show answer
Use log = deque(maxlen=50) and just call log.append(req). When the deque already holds 50 items, appending drops the oldest item from the left end automatically and without an error.
Exercise
Pick the best container for each task and give a one-line reason: (a) the ten most common words in a text, (b) a mapping from each department to the list of its employees, (c) a to-do queue where tasks are added at the back and taken from the front, (d) a table of page titles looked up by page id, where every id is set once.
Show answer
(a) Counter, because most_common(10) does it directly. (b) defaultdict(list), because it creates each department's list on first use. (c) deque, because append and popleft are fast at both ends. (d) A plain dict, because the values are not counts or groups, and a missing id should raise KeyError.