How to solve dictionary changed size during iteration error?

Alternative solutions

If you're looking for the smallest value in the dictionary you can do this:

min(dictionary.values())

If you cannot use min, you can use sorted:

sorted(dictionary.values())[0]

Why do I get this error?

On a side note, the reason you're experiencing an Runtime Error is that in the inner loop you modify the iterator your outer loop is based upon. When you pop an entry that is yet to be reached by the outer loop and the outer iterator reaches it, it tries to access a removed element, thus causing the error.
If you try to execute your code on Python 2.7 (instead of 3.x) you'll get, in fact, a Key Error.

What can I do to avoid the error?

If you want to modify an iterable inside a loop based on its iterator you should use a deep copy of it.


You can use copy.deepcopy to make a copy of the original dict, loop over the copy while change the original one.

from copy import deepcopy

d=dict()
for i in range(5):
    d[i]=str(i)

k=deepcopy(d)

d[2]="22"
print(k[2])
#The result will be 2.

Your problem is iterate over something that you are changing.


In Python3, Try

for key in list(dict.keys()):
    if condition:
        matched
        del dict[key]

1 more thing should be careful when looping a dict to update its key:

Code1:

keyPrefix = ‘keyA’
for key, value in Dict.items():
    newkey = ‘/’.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Code2:

keyPrefix = ‘keyA’
for key, value in Dict.keys():
    newkey = ‘/’.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Result of code1/code2 is:

{‘keyA/keyA/keyB’ : ”, ‘keyA/keyA/keyA’: ”}

My way to resolve this unexpected result:

    Dict = {‘/’.join([keyPrefix, key]): value for key, value in Dict.items()}

Link: https://blog.gainskills.top/2016/07/21/loop-a-dict-to-update-key/