close

[Solved] How to avoid “RuntimeError: dictionary changed size during iteration” error?

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to avoid “RuntimeError: dictionary changed size during iteration” error? in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How How to avoid “RuntimeError: dictionary changed size during iteration” Error Occurs?

Today I get the following error How to avoid “RuntimeError: dictionary changed size during iteration” error? in python.

How To Solve How to avoid “RuntimeError: dictionary changed size during iteration” Error ?

  1. How To Solve How to avoid “RuntimeError: dictionary changed size during iteration” Error ?

    To Solve How to avoid “RuntimeError: dictionary changed size during iteration” Error In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:

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

    To Solve How to avoid “RuntimeError: dictionary changed size during iteration” Error In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:

Solution 1

In Python 3.x and 2.x you can use use list to force a copy of the keys to be made:

for i in list(d):

In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:

for i in d.keys():

But note that in Python 3.x this second method doesn’t help with your error because keys returns an a view object instead of copynig the keys into a list.

Solution 2

You only need to use “copy”:

On that’s way you iterate over the original dictionary fields and on the fly can change the desired dict (d dict). It’s work on each python version, so it’s more clear.

In [1]: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}

In [2]: for i in d.copy():
   ...:     if not d[i]:
   ...:         d.pop(i)
   ...:         

In [3]: d
Out[3]: {'a': [1], 'b': [1, 2]}

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read