Iterating Dicts Forbids Size Changes

Adding or deleting keys while iterating a dict raises RuntimeError after the mutation lands, so structural changes need a key snapshot or a value-only pass.

PythonResilience

Code

pythonsnippet
21 lines
counts = {"a": 1, "b": 2}

# adding a key during iteration raises RuntimeError (keys written in earlier rounds stay in the dict)
try:
    for key in counts:
        counts[key + "!"] = 0
except RuntimeError as err:
    print("add:", type(err).__name__)
print("partial:", counts)

# iterate over a snapshot of the keys before making structural changes
fresh = {"a": 1, "b": 2}
for key in list(fresh):
    if key == "a":
        fresh.pop(key)
print("snapshot loop:", fresh)

# changing the value of an existing key does not raise
for key in fresh:
    fresh[key] = fresh[key] * 10
print("values:", fresh)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

add: RuntimeError
partial: {'a': 1, 'b': 2, 'a!': 0}
snapshot loop: {'b': 2}
values: {'b': 20}

How it works

The file repeats itself only inside for key in counts. A for is raised unconditionally at its raise site — no input check sits in front of it.

Demo state sits in top-level bindings: counts, fresh.

Caveats

  • The standard library is the whole story here — nothing to install at all.

Putting it to use

The demo output is labeled (add:, partial:, snapshot loop:), so the printed lines read as a trace of the operations that ran.

Core lines under the microscope

except RuntimeError as err:
    print("add:", type(err).__name__)

Interactive Tools for This Topic

FAQ

Is there any input checking?
No input check exists: the `for` fires whenever execution reaches its line, not in response to any data shape.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `counts`, `fresh`.