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.

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.
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.
d = {"a": 1, "b": 2, "c": 3}
for k in d:
if k == "b":
del d[k]
# RuntimeError: dictionary changed size during iterationd = {"a": 1, "b": 2}
for k in d:
d[k] = d[k] * 10 # value replacement: allowed| Operation inside the loop | Allowed | Notes |
|---|---|---|
d[k] = new_value for an existing key | yes | no resize |
d[k] = value for a new key | no | RuntimeError |
del d[k] | no | RuntimeError |
d.pop(k) | no | RuntimeError |
d.pop(k, None) for a missing key | yes | no size change |
d.clear() | no | RuntimeError |
d.update(other) | no if it adds keys | RuntimeError |
d.setdefault(k, v) | no if it inserts | RuntimeError |
| mutating a nested list or dict | yes | size of the outer dict unchanged |
| Iteration expression | Snapshot | Safe to mutate the original |
|---|---|---|
for k in d: | no, live view | no |
for k in d.keys(): | no, same view | no |
for k, v in d.items(): | no, live view | no |
for k in list(d): | yes, list of keys | yes |
for k, v in list(d.items()): | yes, list of pairs | yes |
for k, v in d.copy().items(): | yes, shallow copy | yes |
for k in tuple(d): | yes | yes |
Key Comparison Table
| Intent | Wrong | Right |
|---|---|---|
| Remove empty values | delete while iterating | {k: v for k, v in d.items() if v} |
| Remove keys matching a rule | del in a for | list(d) then delete, or rebuild |
| Group into the same dict | setdefault inside iteration | build a new dict, then assign back |
| Normalise values in place | d[k] = f(v) | allowed, no change needed |
| Walk and prune a tree | recursive delete during walk | collect paths, prune after |
| Clear a cache from another thread | cache.clear() during use | cache = {} swap under a lock |
| Merge and dedupe | d.update(...) while iterating | build a fresh dict |
| Symptom | Cause | Fix |
|---|---|---|
| Error on the first delete | key present and removed | snapshot or rebuild |
| Error only with many keys | resize triggered late | same, size check is not the issue |
| Error in a thread but not in tests | concurrent mutation | lock or snapshot |
Error inside json.dumps | default handler mutating | copy before serialising |
| No error, wrong results | value mutated during iteration | acceptable, verify logic |
| Error in a generator | consumer mutates | materialise or lock |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Deleting while iterating
# 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
groups = {}
for row in rows:
groups.setdefault(row.kind, []).append(row) # inserts a new keyThis fails only when the loop iterates groups itself. A frequent shape is a recursive flatten:
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: fineThe 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
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
import threading
cache = {}
lock = threading.Lock()
def evict():
with lock:
for key in list(cache):
if expired(cache[key]):
del cache[key]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
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 objReturning 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
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()orglobals()and assigning. Assigning toglobals()during iteration is the same violation, andlocals()writes are not guaranteed to take effect. - Mutating
os.environbetweenos.environandos.getenv.os.environis a mapping with its own bookkeeping;putenvplus 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
WeakValueDictionarycan 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 documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.