如何避免“RuntimeError:字典在迭代期间改变大小”错误? [英] How to avoid "RuntimeError: dictionary changed size during iteration" error?

查看:127
本文介绍了如何避免“RuntimeError:字典在迭代期间改变大小”错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了所有其他问题,并发现相同的错误,但没有发现没有帮助的解决方案= /



我有一个列表的字典:

  d = {'a':[1],'b':[1,2],'c':[],'d' []} 

其中一些值为空。在创建这些列表的最后,我想在返回我的字典之前删除这些空列表。目前我试图这样做如下:

 对于我在d:
如果不是d [i]:
d.pop(i)

但是,这给我运行时错误。我知道你不能在字典中添加/删除元素,然后再循环一下,然后呢?

解决方案

在Python 2.x调用中创建一个可以迭代的键的副本,同时修改 dict

 为d.keys():
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 the dict:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆