Sub topic 12
Pitfalls: Changing a Dictionary While Iterating
This chapter assumes you know the basics of Python dictionaries: indexing, get(), del, pop(), items(), and comprehensions. You should also know that for loops pull one item at a time from an iterator. The chapter covers why a loop that changes its own dictionary fails, which changes are safe, and which patterns replace the unsafe ones.
The failure
This loop tries to remove every entry with an odd value:
d = {"a": 1, "b": 2, "c": 3}
try:
for k in d:
if d[k] % 2:
del d[k]
except RuntimeError as exc:
print(exc) # dictionary changed size during iteration
print(d) # {'b': 2, 'c': 3}The loop deletes "a" on its first pass. When it asks for the next key, Python raises RuntimeError. The dictionary is left half-processed: "c" has an odd value but was never reached.
Adding keys fails the same way:
d = {"a": 1}
try:
for k in d:
d[k + "x"] = 0
except RuntimeError as exc:
print(exc) # dictionary changed size during iteration
print(d) # {'a': 1, 'ax': 0}The error is raised after the change has already happened. Python does not roll anything back.
Why Python raises the error
A for loop over a dictionary creates a dictionary iterator. The iterator does not copy the keys. It walks the dictionary's internal storage and remembers two things: its position, and the dictionary's size when iteration started.
Each time the loop asks for the next item, the iterator compares the remembered size with the current size. If they differ, it raises RuntimeError. Walking storage that has been rearranged by an insertion or deletion could skip entries or visit them twice, so Python stops instead.
The same applies to the views from keys(), values() and items(). A view is live, so iterating over one is the same as iterating over the dictionary.
d = {"a": 1, "b": 2}
try:
for k, v in d.items():
d.pop(k)
except RuntimeError as exc:
print(exc) # dictionary changed size during iterationWhat is safe and what is not
The check compares sizes, not contents. That gives these rules:
| Operation inside the loop | Result |
|---|---|
| Assign a new value to an existing key | Safe. The size does not change. |
| Mutate a value in place, such as `d[k].append(x)` | Safe. The dictionary itself is untouched. |
| Add a new key | `RuntimeError` on the next step. |
| Delete or pop a key | `RuntimeError` on the next step. |
| `del` or `pop()` followed immediately by `break` or `return` | Safe. The iterator is never asked for another item. |
| Delete one key and add another in the same pass | Undefined. The size matches, so Python may not notice. |
Updating existing values works as expected:
prices = {"apple": 1.0, "pear": 2.0}
for k in prices:
prices[k] *= 2
print(prices) # {'apple': 2.0, 'pear': 4.0}Changing a nested dictionary is also safe, because the outer iterator only tracks the outer size:
users = {"ana": {"visits": 1}, "ben": {"visits": 4}}
for name, info in users.items():
info["visits"] += 1
info["seen"] = True
print(users["ana"]) # {'visits': 2, 'seen': True}Stopping right after a removal is also fine:
d = {"a": 1, "b": 2, "c": 3}
for k in d:
if d[k] == 2:
del d[k]
break
print(d) # {'a': 1, 'c': 3}Safe patterns
All of these patterns separate reading from changing. You finish deciding what to change before you change anything.
Loop over a snapshot
list(d) copies the keys into a list. The loop walks the list, so the dictionary is free to change.
d = {"a": 1, "b": 2, "c": 3}
for k in list(d):
if d[k] % 2:
del d[k]
print(d) # {'b': 2}Use list(d.items()) when you need values too. If you read values from the snapshot, they may be stale by the time you act on them. If the loop changes d[other] and later reads other from the snapshot, it sees the old value. Read from d itself when you need the current state.
Collect first, then change
Gather the keys in one pass, then apply the changes in a second pass:
d = {"a": 1, "b": 2, "c": 3}
to_remove = [k for k, v in d.items() if v % 2]
for k in to_remove:
del d[k]
print(d) # {'b': 2}This separation keeps the logic easy to test, and you can log or check to_remove before applying it.
Build a new dictionary
When the goal is "keep only the entries that match", a comprehension is usually clearest and avoids mutation entirely:
d = {"a": 1, "b": 2, "c": 3}
d = {k: v for k, v in d.items() if v % 2 == 0}
print(d) # {'b': 2}This rebinds the name d to a new object. Other references to the old dictionary still see the old contents. If other code holds a reference and must see the change, update the original in place:
d = {"a": 1, "b": 2, "c": 3}
alias = d
kept = {k: v for k, v in d.items() if v % 2 == 0}
d.clear()
d.update(kept)
print(alias) # {'b': 2}Comparing the options
| Pattern | Extra memory | Keeps object identity | Best for |
|---|---|---|---|
| `for k in list(d)` | One list of keys | Yes | Deleting or adding while looping, with simple logic |
| Collect keys, then change | One list of keys | Yes | Logic you want to inspect or test first |
| Comprehension, rebind name | A whole new dictionary | No | Filtering or transforming |
| Comprehension, then `clear()` and `update()` | A whole new dictionary | Yes | Filtering when other references must see the result |
All of these cost memory proportional to the number of entries, which is rarely a problem. For a dictionary so large that the copy matters, remove entries in batches or keep the data in a structure designed for it.
A hidden insertion: defaultdict
A defaultdict creates a missing entry when you index it. Indexing is a read in your head, but it is an insertion for the dictionary. That makes d[k] dangerous when d is a defaultdict that you are iterating.
from collections import defaultdict
links = defaultdict(list, {"a": ["b"], "b": ["c"]})
try:
for node in links:
for target in links[node]:
print(node, "->", links[target])
except RuntimeError as exc:
print(exc) # dictionary changed size during iterationThe output shows a -> ['c'], then b -> [], and then the error. Looking up links["c"] inserted a new key "c". The inner loop finishes, and the outer iterator notices the size change.
The fix is to read without inserting. Use get() or the in operator, neither of which adds a key:
from collections import defaultdict
links = defaultdict(list, {"a": ["b"], "b": ["c"]})
for node in links:
for target in links[node]:
print(node, "->", links.get(target, []))
# a -> ['c']
# b -> []The inner links[node] is safe because node always comes from the dictionary itself, so the key exists.
Other places the same error appears
- Mutation through a called function. A helper that deletes or inserts into the dictionary you are looping over triggers the error far from the loop. If a loop calls code that might change the dictionary, iterate over a snapshot.
- Callbacks and signals. An event handler that registers or unregisters itself in a dictionary of handlers, while that dictionary is being walked, is a common source. Loop over
list(handlers.values())when dispatching. - Threads. Another thread changing the dictionary during your loop gives the same error, but only sometimes. That makes it hard to reproduce. Take a snapshot under a lock, or give each thread its own copy.
- Sets and lists. Sets raise a similar
RuntimeErrorwhen their size changes during iteration. Lists do not raise, but they silently skip elements when you delete during a loop. The dictionary error is a safety net that lists lack.
Common mistakes
- Suppressing the error. Wrapping the loop in
try/except RuntimeErrorleaves the dictionary half-processed. Fix the loop instead. - Snapshotting the wrong thing.
for k in d.keys()is still a live view. Onlylist(d),list(d.keys()),tuple(d)or similar copy the keys. - Assuming a deleted key vanishes from the snapshot. The snapshot still contains it. If a loop over
list(d)deletesd["x"]and then reaches"x"later,d["x"]raisesKeyError. Check withinor used.pop(k, None). - Reading stale values. A snapshot of
items()holds the values from the moment you copied it. Re-read from the dictionary when earlier iterations may have changed an entry.
Exercise
This function should remove every entry whose value is None from a dictionary, in place, so that every other reference to the dictionary also sees the result. It currently raises RuntimeError. Rewrite it so it works and the caller's dictionary object is the one that changes.
def drop_none(d):
for k, v in d.items():
if v is None:
del d[k]
Show answer
Loop over a snapshot of the keys, or collect the keys first:
def dropnone(d):
for k in list(d):
if d[k] is None:
del d[k]
Another correct version:
def dropnone(d):
for k in [k for k, v in d.items() if v is None]:
del d[k]
Rebuilding with d = {k: v for ...} inside the function would not satisfy the requirement, because it rebinds a local name and leaves the caller's dictionary unchanged. If you prefer a comprehension, finish with d.clear() and d.update(kept).
Exercise
Given d = {"a": 1, "b": 2, "c": 3}, which of these loops raises RuntimeError, and why? (1) for k in d: d[k] += 10. (2) for k in d: d[k.upper()] = d[k]. (3) for k in d: d.pop(k); break.
Show answer
Only (2) raises. It inserts a new key, "A", so the size changes and the iterator fails on its next step. Loop (1) only assigns to existing keys, so the size stays the same. Loop (3) removes a key but exits immediately, so the iterator is never asked for another item.