If you try to change a dictionary while you’re looping through it, Python will stop you with this error. This usually happens when you’re adding or deleting keys during the loop. Let’s look at why this happens and how to fix it.
Description of the Problem
You’re iterating over a dictionary and modifying it at the same time, and Python throws this error:
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict: if key == "b": del my_dict[key]
Output:
RuntimeError: dictionary changed size during iteration
Even if your logic seems correct, this exception appears and halts your script.
Why This Happens
When Python loops through a dictionary, it keeps track of the size. If the size changes while it’s looping, like if you delete a key, Python gets confused and shows an error to prevent mistakes.
This applies to:
- for key in dict
- for key, value in dict.items()
- Even dict.keys() and dict.values() if modified during iteration
Steps to Resolve the Issue
Step 1: Use a Copy of the Keys for Safe Iteration
Instead of modifying the dictionary directly while looping, iterate over a copy of its keys:
for key in list(my_dict.keys()): if key == "b": del my_dict[key]
This avoids the runtime error because you’re not looping over the original dictionary structure.
Step 2: Build a New Dictionary Instead
Another safer and often cleaner approach is to build a new dictionary with filtered items:
filtered_dict = {k: v for k, v in my_dict.items() if k != "b"}
This approach avoids mutation altogether and leads to more predictable results.
Step 3: Mark Keys for Deletion, Then Remove Later
If deletion logic is more complex, first collect the keys to remove, then delete them in a second pass:
to_remove = []
for key in my_dict: if should_remove(key): to_remove.append(key)
for key in to_remove: del my_dict[key]
This avoids modifying the dictionary during iteration and gives you full control over the deletion logic.
Step 4: Be Cautious with .items(), .keys() and .values()
All these views reflect real-time changes to the dictionary. So modifying the dictionary while looping through them will also throw errors. Convert them to list() first if you intend to modify.
Conclusion
This error shows up when you change a dictionary while looping through it. Python blocks it to avoid problems.
To fix it:
- Use list(dict.keys()) or list(dict.items()) to safely loop and modify
- Prefer building a new filtered dictionary if you’re removing elements
- Separate iteration and modification steps for cleaner, safer code
If you’re dealing with complex logic around dictionary iteration and mutation, it might be a good time to hire Python developers who can navigate these nuances efficiently.