How to solve dictionary changed size during iteration error?

后端 未结 8 1981
滥情空心
滥情空心 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

    An alternative solution to dictionary changed size during iteration:

    for key,value in list(dictionary.items()):
        for key1, value1 in list(dictionary.items()): 
                if key1!= key and value > value1:
                    dictionary.pop(key)             
    print (dictionary)  
    

    Better use it with caution! when using this type of code, because list(dictionary.items()) calculated when the complier enters first time to loop. Therefore any change made on dictionary won't affect process inside the current loop.

提交回复
热议问题