Skip to content
Home » RuntimeError: dictionary changed size during iteration

RuntimeError: dictionary changed size during iteration

To solve How to avoid “RuntimeError: dictionary changed size during iteration” error? error follow below methods.

ERROR LOG

Traceback (most recent call last):
File "<string>", line 8, in <module>
RuntimeError: dictionary changed size during iteration

How to solve How to avoid “RuntimeError: dictionary changed size during iteration” error? ?

Iterating over a changing object is considered a dangerous and unsafe programming technique in Python 3. In general, we cannot alter an object while iterating over it; this constraint applies to iterables such as lists and even arrays.

If, on the other hand, a function mutates an object, we must ensure that the function only mutates a copy of the original object, leaving the original object intact. This is one of the most used methods for making changes to objects while iterating through them at the same time.

Method 1: Creating a Shallow Copy of the Dictionary

Python includes the copy() module, which allows us to generate a copy of an object that is not bound to the original object. This allows us to freely edit the item’s duplicate while keeping the original object intact.

It should be noted that in Python, the assignment operator cannot be used to achieve the same result. Using the assignment operator creates a variable that refers to the original object rather than a replica of the original object.

As a result, any changes made to the new object will also affect the original object. This operator is frequently abused by new developers.

sample code:

import copy
cars = {
 "brand": "tata",
 "year":  2021,
 }

#creating a shallow copy
cars_copy = copy.copy(cars)

for x in cars_copy.keys():
    cars["color"] = "white"
    
print(cars)
print(cars_copy)

Method 2 : Casting Dictionary Items to a List

Because we cannot loop over the dictionary while changing it, we can instead create a casting list and iterate over it while changing the dictionary. Iterating through the casting list rather than the original dictionary produces no Runtime errors.

sample code:

cars = {
 "brand": "tata",
 "year":  2021,
 }

for i in list(cars):
    cars["color"] = "white"
    
print(cars)

Hope the above solution works.

Also read :

ImportError: No module named psycopg2
socket.error: [Errno 111] Connection refused Python