Sub topic 12
Pitfalls: changing a dictionary while iterating
This chapter assumes you can write for loops, know that dictionaries are mutable, and have used del, pop() and items(). It covers one common error: changing a dictionary's size while a loop is reading it.
The error
Looping over a dictionary reads it as it goes. If the loop adds or removes a key, Python notices that the dictionary no longer matches what the loop started with. It stops with a RuntimeError.
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 iterationThe same error appears for d[new_key] = ..., pop(), popitem(), setdefault() with a new key, and update() with new keys. Anything that changes the number of keys can trigger it.
A related message is "dictionary keys changed during iteration". It appears when a loop removes one key and adds another, so the size stays the same but the key set differs.
Why Python raises it
A dictionary view such as keys() or items() is a live window onto the dictionary. It is not a snapshot. The loop walks through the internal storage in order. Adding or removing an entry can move things around, so the loop could skip entries or visit them twice. Python keeps a size check and raises an error instead of returning wrong results.
flowchart TDSafe pattern: loop over a copy of the keys
Wrap the dictionary in list(). This builds a separate list of the keys at that moment. The loop reads the list, so you are free to change the dictionary.
d = {"a": 1, "b": 2, "c": 3}
for k in list(d):
if d[k] % 2:
del d[k]
print(d) # {'b': 2}For large dictionaries the copy costs memory, but only for the keys, not the values.
Safe pattern: build a new dictionary
Often you do not need to change the original. A comprehension keeps the entries you want and gives you a new dictionary.
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 is usually the clearest choice. It also avoids a second bug: other references to the old dictionary keep their original contents, which is safer when the dictionary is shared.
Safe pattern: collect, then change
You can also record what to change in the first loop and apply it afterwards.
inventory = {"apple": 0, "pear": 4, "kiwi": 0}
empty = [name for name, count in inventory.items() if count == 0]
for name in empty:
del inventory[name]
print(inventory) # {'pear': 4}Updating values is allowed
Changing the value of a key that already exists does not change the size, so it is safe during iteration.
prices = {"apple": 0.5, "pear": 0.75}
for item in prices:
prices[item] = round(prices[item] * 1.1, 2)
print(prices) # {'apple': 0.55, 'pear': 0.82}Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| `for k in d: del d[k]` | `RuntimeError` | `for k in list(d):` |
| Adding a key inside `for k in d` | `RuntimeError` | Collect new entries, then `d.update(new)` after the loop |
| Using `d.keys()` and expecting a copy | Same error, since views are live | Use `list(d.keys())` |
| Using `list(d.values())` to find keys to delete | You have values but no keys | Loop over `list(d.items())` |
Exercise
You have stock = {"apple": 3, "pear": 0, "kiwi": 7, "fig": 0}. Write code that removes every item whose count is 0 from stock itself (not a new dictionary), without raising an error.
Show answer
Loop over a copy of the keys: for name in list(stock): if stock[name] == 0: del stock[name] Afterwards stock is {'apple': 3, 'kiwi': 7}. Looping over stock directly would raise RuntimeError because deleting changes its size.
Exercise
Why does for k in d: d[k] = d[k] * 2 run without an error, while for k in d: d[k + "x"] = 0 fails?
Show answer
The first loop only replaces values for keys that already exist, so the dictionary size stays the same. The second loop adds new keys, which changes the size, so Python raises RuntimeError.