1. 程式人生 > >python-遇到dictionary changed size during iteration

python-遇到dictionary changed size during iteration

轉換 con continue average cti dict 大小 div change

 1 c=0
 2 f={}
 3 jiao={腳本一:122000,腳本二:189999,
 4        腳本三:99999,腳本4:25000000,jiaoben:126}
 5 for i in jiao.values():
 6     c=c+i
 7 average=c/len(jiao)
 8 for li in jiao.keys():
 9     if jiao[li]>average:
10         del jiao[li]
11 # f.setdefault(li,jiao[li])
12 print(average)
13 print(li)

此時運行出現一下錯誤:

RuntimeError: dictionary changed size during iteration # 字典在叠代的時候改變了字典大小

這個問題在網上找的兩種方法:1.是通過轉換成列表進行刪除;

             2.一下為網上拷貝

for key in result.keys(): # 由 result 變為 result.keys()

    if not result[key]:

        del result[key]

        continue

第二種經過測試並沒有解決問題,警告依然存在,

解決辦法是不對它進行刪除,對不刪除的數據重新賦值給一個新的字典.

python-遇到dictionary changed size during iteration