RuntimePython Error

RuntimeError

RuntimeError: dictionary changed size during iteration

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    del scores[key]
RuntimeError: dictionary changed size during iteration

What causes this error

Dictionary keys were added or deleted during iteration, invalidating the iterator. Python detects this change and raises RuntimeError to prevent undefined behavior.

How to fix it

Iterate over a copy of the keys: `for key in list(d.keys())`. Use dictionary comprehensions to filter. Collect keys to delete in a separate list and remove them after iteration.

Code that causes this error

Broken
scores = {"a": 1, "b": 5, "c": 2}
for key in scores:
    if scores[key] < 3:
        del scores[key]

Fixed code

Fixed
scores = {"a": 1, "b": 5, "c": 2}
scores = {k: v for k, v in scores.items() if v >= 3}
# or: for key in list(scores.keys()): ...

About RuntimeError

This RuntimeError is raised when you add or remove keys from a dictionary while iterating over it. Python dictionaries maintain an internal version counter, and the iterator checks this counter on each step — if the size changed, iteration cannot safely continue because the internal hash table may have been restructured. This same error applies to sets (which use a similar hash table internally).

The error was introduced as a safety check to prevent undefined behavior — in older Python versions, modifying a dict during iteration could cause silently skipped or duplicated entries. The standard fix is to iterate over a copy of the keys: `for key in list(d.keys())`. For more complex filtering operations, use dictionary comprehensions to create a new dict with only the desired entries.

Common scenarios

1

Infinite recursion from missing or incorrect base cases

2

Modifying dictionaries or sets during iteration

3

Calling generators or coroutines in unsupported ways

4

Using asyncio event loops incorrectly or attempting to nest them

Related errors