How to avoid RuntimeError dictionary changed size during iteration error?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The RuntimeError: dictionary changed size during iteration occurs when you add or remove keys from a dictionary while iterating over it with a for loop. Python raises this error because modifying the dictionary's size invalidates the iterator. The fix is to iterate over a copy of the keys (list(d.keys())), use a dictionary comprehension to create a new dictionary, or collect keys to modify and apply changes after the loop.
The Error
Python detects that the dictionary's size changed during iteration and raises RuntimeError to prevent undefined behavior.
Fix 1: Iterate Over a Copy of Keys
Create a snapshot of the keys before iterating:
list(data.keys()) creates an independent list of keys at that moment. Deleting from data does not affect the list being iterated.
Fix 2: Dictionary Comprehension (Create New Dict)
Build a new dictionary with only the desired entries:
This is the most Pythonic approach for filtering. It creates a new dictionary without modifying the original during iteration.
Fix 3: Collect Keys, Then Modify
Separate the iteration and modification into two steps:
This is useful when deletion logic is complex or has side effects.
Fix 4: Copy with dict() or .copy()
Both dict(data) and data.copy() create shallow copies. The loop iterates over the copy while modifications happen on the original.
Adding Keys During Iteration
The error also occurs when adding new keys:
Modifying Values Is Safe
Changing existing values does not change the dictionary's size, so it is allowed:
Only adding new keys or deleting existing keys triggers the error.
Nested Dictionary Iteration
Apply list() on the inner dictionary's keys, not the outer one (unless you are modifying both).
defaultdict and Counter
The same error applies to defaultdict and Counter:
Common Pitfalls
- Iterating over
data.keys()instead oflist(data.keys()): In Python 3,dict.keys()returns a view, not a copy. The view reflects changes to the dictionary, so deleting during iteration still raises the error. Wrap inlist()to create an independent copy. - Forgetting that
for key in dataiterates over keys:for key in datais equivalent tofor key in data.keys(). Both return a view that is invalidated by size changes. Always copy before modifying. - Assuming modifying a value triggers the error: Only structural changes (add/delete keys) trigger the error.
data[key] = new_valuefor an existing key is safe because the dictionary size does not change. - Using
data.copy()for deeply nested dictionaries:.copy()creates a shallow copy. If you modify nested dictionaries inside the copy, the changes affect the original too. For deep structures, usecopy.deepcopy()if you need full isolation. - Catching
RuntimeErrorinstead of fixing the iteration: Wrapping the loop intry/except RuntimeErrorhides the bug and may skip items. Fix the iteration pattern instead of suppressing the error.
Summary
- The error occurs when adding or deleting dictionary keys during iteration
- Use
list(data.keys())to iterate over a copy of keys - Use dictionary comprehensions to create a filtered new dictionary
- Collect keys to delete in a separate list, then delete after the loop
- Modifying existing values (without adding/deleting keys) is always safe

