How to fix “RuntimeError: dictionary changed size during iteration”

RuntimeError: dictionary changed size during iteration

In this article, we will discuss what causes the “RuntimeError: dictionary changed size during iteration” error. In addition, you will know how to use copy(), keys() and some other methods to deal with this error, follow the details below.

What is the “RuntimeError: dictionary changed size during iteration” error?

In Python, RuntimeError is classed as exception error types. Errors usually occur when there is a problem with the logic of the program. Usually it’s pretty hard to spot while you’re coding. Suppose in this situation, when you enter the following program, the error “RuntimeError: dictionary changed size during iteration” occurred:

Error code

student = {
	"firstName": "Liza",
	"lastName": "Nguyen",
 	"yearofBirth": 2000
}

for s in student.keys():
    student["department"] = "IT"

print("student:", student)

Output:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-61-6bbcf4bfc185> in <module>
      5  }
      6 
----> 7 for s in student.keys():
      8     student["department"] ="IT"
      9 

RuntimeError: dictionary changed size during iteration

What causes error?

The error “RuntimeError: dictionary changed size during iteration” informs the coder that: During the execution of the loop instruction, the size of the visible word has been changed. That is, you cannot make modifications while iterating, which will cause a runtime error.

How to fix it?

To help you quickly and effectively solve the above error, we have summarized some methods below. Let’s take a look and choose the method that is suitable for you.

Solution 1: Using copy() function

The purpose of this method is that you can use the copy() function that Python provides to create a new copy that is not affected by the original. From there you can easily edit the copy while keeping the original.

For example:

import copy

student = {
 	"firstName": "Liza",
 	"lastName": "Nguyen",
 	"yearofBirth": 2000
}
copyStudent = copy.copy(student)
for s in copyStudent.keys():
    student["department"] = "IT"

print("student:", student)
print("copyStudent:", copyStudent)

Output:

student: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000, 'department': 'IT'}
copyStudent: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000}

Solution 2: Using keys() function

With this method, we will create a list of keywords in the dictionary and after returning the result will be a new unaffected list.

For instance:

student = {
 	"firstName": "Liza",
 	"lastName": "Nguyen",
 	"yearofBirth": 2000
}

keyStudent = list(student.keys())
print("keyStudent", keyStudent)

for key in keyStudent:
	if key == "yearofBirth":
    	student[key] = 2001
        
print("student", student)

Output:

keyStudent ['firstName', 'lastName', 'yearofBirth']
student {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2001}

Solution 3: Use the ** operator

This method will take the key-value pairs from one dictionary and pass it to another dictionary. This is also another way to get a copy of a dictionary or list.

Code sample:

student = {
   "firstName": "Liza",
   "lastName": "Nguyen",
   "yearofBirth": 2000
}

copyStudent = {**student}
for s in copyStudent.keys():
    student["department"] = "IT"

print("student:", student)
print("copyStudent:", copyStudent)

Output

student: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000, 'department': 'IT'}
copyStudent: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000}

Solution 4: Pass the new dictionary object to the list

With this method, by creating a cast list and manipulating changes through it, the iteration won’t cause the above error.

For example:

student = {
   "firstName": "Liza",
   "lastName": "Nguyen",
   "yearofBirth": 2000
}

for lst in list(student):
    student["department"] = "IT"

print("student:", student)

Output

student: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000, 'department': 'IT'}

Conclusion

This is how you are able to solve this type of task “RuntimeError: dictionary changed size during iteration”. However, we have provided relevant expertise to develop a more research-oriented mindset, and make it easier for you to answer these type questions. Please leave a message below if you have any questions or comments. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *