How to solve dictionary changed size during iteration error?

后端 未结 8 1970
滥情空心
滥情空心 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 02:00

    As I read your loop right now, you're looking to keep only the single smallest element, but without using min. So do the opposite of what your code does now, check if value1 < minValueSoFar, if so, keep key1 as minKeySoFar. Then at the end of the loop (as Zayatzz suggested), do a dictionary.pop(minKeySoFar)

    As an aside, I note that the key1!=key test is irrelevant and computationally inefficient assuming a reasonably long list.

    minValueSoFar = 9999999;   # or whatever
    for key,value in dictionary.items():
        if value < minValueSoFar:
            minValueSoFar = value
            minKeySoFar = key
    dictionary.pop(minKeySoFar)   # or whatever else you want to do with the result
    

提交回复
热议问题