如何避免“RuntimeError:字典在迭代期间改变大小”错误? [英] How to avoid "RuntimeError: dictionary changed size during iteration" error?
问题描述
我有一个列表的字典:
d = {'a':[1],'b':[1,2],'c':[],'d' []}
其中一些值为空。在创建这些列表的最后,我想在返回我的字典之前删除这些空列表。目前我试图这样做如下:
对于我在d:
如果不是d [i]:
d.pop(i)
但是,这给我运行时错误。我知道你不能在字典中添加/删除元素,然后再循环一下,然后呢?
在Python 2.x调用键
中创建一个可以迭代的键的副本,同时修改 dict
:
为d.keys():
$请注意,这在Python 3.x中不起作用,因为
keys
返回一个迭代器而不是一个列表。
另一种方法是使用
列表
强制复制密钥。这个还可以在Python 3.x中使用:对于列表(d)中的i:
I have checked all of the other questions with the same error yet found no helpful solution =/
I have a dictionary of lists:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
in which some of the values are empty. At the end of creating these lists, I want to remove these empty lists before returning my dictionary. Current I am attempting to do this as follows:
for i in d: if not d[i]: d.pop(i)
however, this is giving me the runtime error. I am aware that you cannot add/remove elements in a dictionary while iterating through it...what would be a way around this then?
解决方案In Python 2.x calling
keys
makes a copy of the key that you can iterate over while modifying thedict
:for i in d.keys():
Note that this doesn't work in Python 3.x because
keys
returns an iterator instead of a list.Another way is to use
list
to force a copy of the keys to be made. This one also works in Python 3.x:for i in list(d):
这篇关于如何避免“RuntimeError:字典在迭代期间改变大小”错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!