How to solve dictionary changed size during iteration error?

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

提交回复
热议问题