How to solve dictionary changed size during iteration error?

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

    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.

    0 讨论(0)
  • 2020-12-06 02:02

    Record the key during the loop and then do dictionary.pop(key) when loop is done. Like this:

    for key,value in dictionary.items():
        for key1, value1 in dictionary.items(): 
                if key1!= key and value > value1:
                    storedvalue = key
        dictionary.pop(key)  
    
    0 讨论(0)
提交回复
热议问题