RuntimeError Dictionary Changed Size During Iteration

RuntimeError: dictionary changed size during iteration occurs when we changed the size of the dictionary during the execution/using for loop. The problem can be easily solved by copying the dictionary and then iterating over it. This short article will discuss how we can solve RuntimeError: dictionary changed size during iteration error using various methods. Moreover, we will also cover how to interpret errors in Python so that in the future we can easily solve the errors.

RuntimeError: Dictionary Changed Size During Iteration

How to Solve RuntimeError: Dictionary Changed Size During Iteration?

The RuntimeError: dictionary changed size during iteration error occurs when we changed the size of the dictionary during iterations. The iteration can be either using the for loop or the while loop. The simplest way to get rid of RuntimeError: dictionary changed size during iteration error is to copy the dictionary and use the copied one in the iteration.

For example, let us assume that we want to delete any key from the dictionary based on some conditions:

# defining a dictionary
dic = {'a': 1, 'b': 2, 'c': 3}

# using for loop to iterate through the dict
for key in dic:
    if key == 'c':
        
        # deleting the key
        del dic[key]

Output:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_206558/2152158728.py in <module>
      3 
      4 # using for loop to iterate through the dict
----> 5 for key in dic:
      6     if key == 'c':
      7 

RuntimeError: dictionary changed size during iteration

The reason for getting this error is that we are iterating over the dictionary and it is not allowed to change the size of the dictionary while iterating through it. If we want to delete the elements from the dictionary based on some condition, then we need to copy the dictionary and iterate through it:

Another important thing about Python errors is that they show you the exact line where the error has occurred. For example, in our case, it is directed to line 5 where our for loop is located. From this, you can directly guess that there is something wrong inside the for loop.

Solution-1: Use copy() method

As we said, one of the simplest methods to get rid of RuntimeError: dictionary changed size during iteration error is to copy the original dictionary and then iterate through the copy and make changes in the original based on the conditions:

For example, see below how we have used the copy() method to copy the dictionary.

# defining a dictionary
dic = {'a': 1, 'b': 2, 'c': 3}

# using for loop to iterate through the dict
for key in dic.copy():
    if key == 'c':
        
        # deleting the key
        del dic[key]

Notice that we are iterating through the copied dictionary and making changes in the original based on the given conditions.

Solution-2: Changing the Dictionary to a List

Another alternative method is to convert the keys of the dictionary into a list and iterate over them and make changes in the dictionary accordingly. The difference between a list and a dictionary in Python is that a dictionary is the combination of key-value pairs while there is no pairing in lists.

# defining a dictionary
dic = {'a': 1, 'b': 2, 'c': 3}

# using for loop to iterate through the dict
for key in list(dic.keys()):
    if key == 'c':
        
        # deleting the key
        del dic[key]

As you can see, in the for loop we created a list of keys from the dictionary and are iterating over them. Running this code will not cause RuntimeError: dictionary changed size during iteration error anymore.

Solution-3: Using dic.items()

In a similar way to the above solution, we can also use dic.items() method as well. The dic.items() method returns a list of tuples as shown below:

# defining a dictionary
dic = {'a': 1, 'b': 2, 'c': 3}

# dic items()
dic.items()

Now, let us see how we can use this method to solve RuntimeError: dictionary changed size during iteration error.


# defining a dictionary
dic = {'a': 1, 'b': 2, 'c': 3}

# using for loop
for key, value in list(dic.items()):
    if key == 'b':
        del dic[key]

Now, you will not get the error anymore.

There can be many other alternative methods to solve the error as well depending on the reason for getting the error. But if you understood and are able to locate the error in your program, then it becomes easy to solve the issue.

Understanding the RuntimeError: dictionary changed size during iteration error

Let us now understand what this error means and why we are getting it. In Python, usually, the errors have two parts. The first part of the error gives us information about the category of the error. In our case, the error belongs to RunTimeError which means the code is absolutely fine but the problem occurs while running the code. The second part of the error gives more specific details about the error. In our case, it explains why we are getting RuntimeError. It clearly says the dictionary changed size during iteration which means we have applied iteration over the dictionary and are changing its size during execution.

What Does RunTimeError Mean in Python?

A RunTimeError in Python is a type of error that occurs during the execution of the Python code. This error shows that everything ( including syntax ) is correct in the code, but due to technical errors, the script could not be executed. The Python script will run and then it will face an error while executing which is sometimes difficult to handle.

The best practice to get rid of RunTimeError is to use the try-except block which actually is there to handle RunTimeError. The code inside the try block will be first executed and if any error occurs while executing the code, then rather than crashing the script, the code inside the except block will be executed. Again, here it is important to locate and predict in which block of the code, the chances of getting errors are high so that you can place that code inside the try block.

Summary

In this short article, we discussed how we can solve RuntimeError: dictionary changed size during iteration error using various methods. Mainly, we discussed three different methods to solve the issue along with examples. Moreover, we also discussed how to interpret Python errors and understand them.

Related Errors

Leave a Comment

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

Scroll to Top