python-遇到dictionary changed size during iteration

Posted leo-tail-x

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-遇到dictionary changed size during iteration相关的知识,希望对你有一定的参考价值。

 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的主要内容,如果未能解决你的问题,请参考以下文章

python 报错RuntimeError: dictionary changed size during iteration

Python面试题目之(针对dict或者set数据类型)边遍历 边修改 报错dictionary changed size during iteration

dict遍历的时候删除dict中的值报错RuntimeError: dictionary changed size during iteration

字典遍历过程中修改字典元素,报错 RuntimeError: dictionary changed size during iteration

遇到问题--python---RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility.(

遇到问题--python---RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility.(