ProjectStack
python

RuntimeError: dictionary changed size during iteration

You tried to add or remove keys from a dictionary while iterating over it. Python detects this and raises an error to prevent unpredictable behavior during the loop.

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

  1. Iterate over a copy of the keys: for key in list(my_dict.keys()):
  2. Or copy the whole dict: for key in dict(my_dict):
  3. 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]
  4. 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 iteration

Deleting 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.