Common causes
- Deleting keys inside a for key in my_dict: loop
- Adding new keys to the dictionary inside the loop body
- A helper function called inside the loop modifies the same dictionary
- Iterating a shared dictionary while another thread modifies it
How to fix it
- Iterate over a copy of the keys: for key in list(my_dict.keys()):
- Or copy the whole dict: for key in dict(my_dict):
- Collect keys to delete first, then delete after the loop: to_delete = [k for k in d if condition]; for k in to_delete: del d[k]
- Use a dictionary comprehension to build a new filtered dict: new_dict = {k: v for k, v in d.items() if condition}
Example
Traceback (most recent call last):
File "app.py", line 4, in <module>
for key in data:
RuntimeError: dictionary changed size during iterationDeleting expired entries from a cache dictionary inside a for key in cache: loop
Have a different error?
Paste any error message into the Error Translator to get an instant explanation.
