How to Fix: RuntimeError: dictionary changed size during iteration

3D illustration of a conveyor belt jamming because items were added or removed while moving, representing a dictionary iteration error.

Imagine you have a list of tasks, and you’re crossing them off one by one. If someone suddenly ripped half the page out while you were reading it, you’d get confused. That’s exactly what happens to Python here, resulting in a RuntimeError because the dictionary changed size during iteration.

The Cause

You are looping through a dictionary and trying to add or delete keys inside that same loop.

Problem Code:

scores = {"Alice": 50, "Bob": 85, "Charlie": 40}
for student, score in scores.items():
    if score < 60:
        # CRASH! You can't delete 'Alice' while you are currently looking at 'Alice'
        del scores[student]

The Fix: Iterate Over a Copy

You need to loop over a static list of the keys, not the live dictionary itself. You can get a static list by converting .keys() or .items() to a list(). This prevents encountering the RuntimeError dictionary changed size.

scores = {"Alice": 50, "Bob": 85, "Charlie": 40}
# Create a separate LIST of keys to loop over
# list(scores.keys()) creates ['Alice', 'Bob', 'Charlie']
for student in list(scores.keys()):
    if scores[student] < 60:
        del scores[student]  # This is now safe!
print(scores)
# Output: {'Bob': 85}

Now, you are reading from the static list, but deleting from the actual dictionary. No confusion and no more RuntimeError surprises!

Similar Posts

Leave a Reply