python
runtime_error
ai_generated
true
RuntimeError: dictionary changed size during iteration
ID: python/runtimeerror-dict-changed-size
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Modifying a dict while iterating over it. Also applies to sets.
genericWorkarounds
-
95% success Iterate over a copy: for k in list(d.keys()): del d[k]
for key in list(my_dict.keys()): if condition: del my_dict[key]Sources: https://docs.python.org/3/library/stdtypes.html#dict
-
92% success Build a new dict with dict comprehension instead of modifying in place
filtered = {k: v for k, v in d.items() if condition}Sources: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Dead Ends
Common approaches that don't work:
-
Use try/except RuntimeError to catch and continue
85% fail
Silences the error but iteration results are undefined
-
Switch to a different dict implementation
70% fail
All Python dicts have this restriction
Error Chain
Frequently confused with: