python 报错RuntimeError: dictionary changed size during iteration

Posted lonelyshy

tags:

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

1 a = {1:11, 2:0, 3:0}
2 for b in list(a.keys()):
3     if a[b] == 0:
4         del a[b]
5 
6 print(a)

报错是因为在字典迭代期间改变字典大小

 

我们可以通过取出字典的键值,在转化为列表,这样在for循环期间就可以删除了

 

以上是关于python 报错RuntimeError: dictionary changed size during iteration的主要内容,如果未能解决你的问题,请参考以下文章