python runtime_error ai_generated true

RuntimeError: dictionary changed size during iteration

ID: python/runtimeerror-dict-changed-size

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Modifying a dict while iterating over it. Also applies to sets.

generic

Workarounds

  1. 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

  2. 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:

  1. Use try/except RuntimeError to catch and continue 85% fail

    Silences the error but iteration results are undefined

  2. Switch to a different dict implementation 70% fail

    All Python dicts have this restriction

Error Chain

Frequently confused with: