Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: dictionary changed size during iteration

Deleting or adding keys while looping over a dict invalidates the iterator. Snapshot the keys, rebuild the dict or lock shared state first.

~5 min readPython
#python#runtime-error#dict#iteration
Bold white headline reading DICT CHANGED beside a cyan Python dict grid with one amber inserted cell.

Introduction & Quick Summary

A cleanup function crashes on data that looks harmless:

RuntimeError: dictionary changed size during iteration

Quick answer: the dictionary was modified while a for loop was iterating it. Python's dict iterator checks the dict's size on every step, and any insert or delete invalidates it immediately.

python
for key in list(data): # snapshot first if data[key] is None: del data[key]

Changing a value for an existing key is allowed; adding or removing a key is not. The error is one of the most common Python runtime failures because the offending code often looks correct: del inside a loop, setdefault while grouping, a thread clearing a cache, or a recursive walk that prunes as it goes. This guide covers each pattern, why list comprehensions and list() work, and the cases where the snapshot itself is a bug.

Core Mechanics, Signatures & Reproducible Setup

dict iteration yields keys from a hash table. Mutations that resize or reorder the table set a version counter, and the iterator raises rather than producing an inconsistent sequence.

python
d = {"a": 1, "b": 2, "c": 3} for k in d: if k == "b": del d[k] # RuntimeError: dictionary changed size during iteration
python
d = {"a": 1, "b": 2} for k in d: d[k] = d[k] * 10 # value replacement: allowed
Operation inside the loopAllowedNotes
d[k] = new_value for an existing keyyesno resize
d[k] = value for a new keynoRuntimeError
del d[k]noRuntimeError
d.pop(k)noRuntimeError
d.pop(k, None) for a missing keyyesno size change
d.clear()noRuntimeError
d.update(other)no if it adds keysRuntimeError
d.setdefault(k, v)no if it insertsRuntimeError
mutating a nested list or dictyessize of the outer dict unchanged
Iteration expressionSnapshotSafe to mutate the original
for k in d:no, live viewno
for k in d.keys():no, same viewno
for k, v in d.items():no, live viewno
for k in list(d):yes, list of keysyes
for k, v in list(d.items()):yes, list of pairsyes
for k, v in d.copy().items():yes, shallow copyyes
for k in tuple(d):yesyes

Key Comparison Table

IntentWrongRight
Remove empty valuesdelete while iterating{k: v for k, v in d.items() if v}
Remove keys matching a ruledel in a forlist(d) then delete, or rebuild
Group into the same dictsetdefault inside iterationbuild a new dict, then assign back
Normalise values in placed[k] = f(v)allowed, no change needed
Walk and prune a treerecursive delete during walkcollect paths, prune after
Clear a cache from another threadcache.clear() during usecache = {} swap under a lock
Merge and deduped.update(...) while iteratingbuild a fresh dict
SymptomCauseFix
Error on the first deletekey present and removedsnapshot or rebuild
Error only with many keysresize triggered latesame, size check is not the issue
Error in a thread but not in testsconcurrent mutationlock or snapshot
Error inside json.dumpsdefault handler mutatingcopy before serialising
No error, wrong resultsvalue mutated during iterationacceptable, verify logic
Error in a generatorconsumer mutatesmaterialise or lock

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Deleting while iterating

python
# wrong for key, value in settings.items(): if value is None: del settings[key] # right: rebuild settings = {k: v for k, v in settings.items() if v is not None} # right: snapshot when the dict is mutated elsewhere for key in list(settings): if settings[key] is None: del settings[key]

Rebuilding is usually clearer and avoids the question of partial mutation. The snapshot version is right when other references must see the same object updated in place.

2. Adding keys during a walk

python
groups = {} for row in rows: groups.setdefault(row.kind, []).append(row) # inserts a new key

This fails only when the loop iterates groups itself. A frequent shape is a recursive flatten:

python
def flatten(node, out): for key, value in node.items(): if isinstance(value, dict): flatten(value, out) else: out[key] = value # out is a different dict: fine

The error appears when out is the same dict being iterated. Accumulate into a new dict and assign at the end.

3. items() is a view, not a list

python
d = {"a": 1, "b": 2} view = d.items() # live view d["c"] = 3 list(view) # [('a', 1), ('b', 2), ('c', 3)]

Python 3 returns views, so storing d.items() does not protect against later changes. Code ported from Python 2, where d.items() returned a list, often relies on the snapshot without noticing.

4. Shared dicts across threads and tasks

python
import threading cache = {} lock = threading.Lock() def evict(): with lock: for key in list(cache): if expired(cache[key]): del cache[key]
python
async def handle(request): for key in list(state): if state[key].stale: state.pop(key)

Async code has the same problem without threads: an await inside the loop lets another task mutate the dict. Snapshot before the first await, or protect the mutation with asyncio.Lock. Rebinding cache = {} is atomic in CPython and is a safe way to clear a shared dict when readers only keep a local reference.

5. Recursive traversal and json handling

python
def prune(obj): if isinstance(obj, dict): return {k: prune(v) for k, v in obj.items() if v is not None} if isinstance(obj, list): return [prune(v) for v in obj] return obj

Returning new containers avoids mutation entirely and is safe for JSON-like data. When a default= handler in json.dumps mutates the object being serialised, the same error surfaces from inside the encoder; copy the object first.

6. Safe patterns and their costs

python
for key in tuple(d): # immutable snapshot, cheaper than list for small dicts for key, value in dict(d).items(): keys_to_delete = [k for k, v in d.items() if v is None] for k in keys_to_delete: del d[k]

list(d) allocates one list; dict(d) copies values and keys; the two-pass approach allocates only the keys that will be removed. For a dict with millions of entries, prefer a comprehension that builds the result once, or delete in batches. Use the JSON formatter to inspect the payload you are cleaning, and the CSV to JSON converter when the same transformation runs on tabular input.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Only fixing the line the traceback names. The mutation may happen in a helper called from the loop; read the loop, not just the del.
  • Assuming d.copy() is deep. It copies the mapping, not nested values; mutating a nested dict during iteration of the copy is fine, but iterating the nested dict itself is not.
  • Iterating locals() or globals() and assigning. Assigning to globals() during iteration is the same violation, and locals() writes are not guaranteed to take effect.
  • Mutating os.environ between os.environ and os.getenv. os.environ is a mapping with its own bookkeeping; putenv plus iteration can produce inconsistent views.
  • Relying on implementation details. CPython raises on size change; PyPy and other implementations may behave differently, so the error does not appear in one environment and appears in another.
  • Python 3.8 and later ordering. Insertion order is guaranteed, but the error is about size, not order; reordering by deleting and reinserting a key still raises.
  • Weakref dictionaries and caches. A WeakValueDictionary can shrink during iteration when the garbage collector runs, which produces the same error in code that never deletes a key.

The rule to remember is simple: iterate a snapshot when the loop can change the mapping, and prefer building a new dict when the transformation is expressible as a comprehension. That removes the error and usually reads better.

Official documentation: built-in types: dict and the expressions reference.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.