RuntimeError: dictionary changed size during iteration

avatar

Borislav Hadzhiev

Sat Apr 30 20222 min read

RuntimeError: dictionary changed size during iteration #

The Python "RuntimeError: dictionary changed size during iteration" occurs when we change the size of a dictionary when iterating over it. To solve the error, use the copy() method to create a shallow copy of the dictionary that you can iterate over, e.g. my_dict.copy().

runtimeerror dictionary changed size during iteration

Here is an example of how the error occurs.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} # ⛔️ RuntimeError: dictionary changed size during iteration for key in my_dict: print(key) if key == 'b': del my_dict[key]

It is not allowed to change the size of a dictionary while iterating over it.

One way to solve the error is to use the dict.copy method to create a shallow copy of the dictionary and iterate over the copy.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict.copy(): print(key) if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}
Iterating over a dictionary and changing its size messes up with the iterator, so creating a shallow copy and iterating over the copy solves the issue.

You can also convert the keys of the dictionary to a list and iterate over the list of keys.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in list(my_dict.keys()): print(key) if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}

The dict.keys method returns a new view of the dictionary's keys.

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.keys()) # 👉️ dict_keys(['id', 'name'])

We used the list() class to create a copy of the keys in the example.

You can also use the dict.items() method in a similar way.

However, notice that when using dict.items(), we have access to the key and value of the current iteration.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in list(my_dict.items()): print(key, value) # 👉️ a 1, b 2, c 3 if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}

We used the list() class to create a copy of the dictionary's items.

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'Alice')])

Which approach you pick is a matter of personal preference. I'd go with using the dict.copy() method.

The method returns a shallow copy of the dictionary, so it's quite easy to read and solves the issue of not being able to iterate over a dictionary and change its size.

Use the search field on my Home Page to filter through my more than 1,000 articles.