How to solve dictionary changed size during iteration error?

后端 未结 8 1980
滥情空心
滥情空心 2020-12-06 01:40

I want pop out all the large values and its keys in a dictionary, and keep the smallest. Here is the part of my program

for key,value in dictionary.items():
         


        
8条回答
  •  感动是毒
    2020-12-06 01:57

    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.

提交回复
热议问题