. Advertisement .
..3..
. Advertisement .
..4..
This is the program I run:
for key,value in dictionary.items():
for key1, value1 in dictionary.items():
if key1!= key and value > value1:
dictionary.pop(key)
print (dictionary)
After I run, it returns an error:
RuntimeError: dictionary changed size during iteration
Does anyone have any suggestions for the problem below: runtimeerror: dictionary changed size during iteration in the python. How to solve dictionary changed size during iteration error?
The cause:
The reason of this error is that in the inner loop you modify the iterator your outer loop is based upon. When you pop an entry that the outer loop doesn’t reach but the outer iterator reaches it, it will try to access a removed element, so the error happens.
Solution:
If you want to modify an iterable inside a loop based on its iterator ,you need to use its deep copy .
If you’re finding the smallest value in the dictionary you can do this:
If you cannot use min, you can use:
Python3:
Another thing to be aware of when looping a script to update its key is:
Code1:
Code2:
Code1/code2 results are:
This is how I solved this unanticipated result
Link: https://blog.gainskills.top/2016/07/21/loop-a-dict-to-update-key/