从python中的字典中删除某些键 [英] Remove certain keys from a dictionary in python

查看:431
本文介绍了从python中的字典中删除某些键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个包含一系列集合的字典:

I'm trying to construct a dictionary that contains a series of sets:

{Field1:{Value1, Value2, Value3}, Field2{Value4}}

麻烦的是,我想删除任何字段在集合中只有一个值的字典。我一直在写这样的代码:

The trouble is, I then wish to delete any fields from the dictionary that only have one value in the set. I have been writing code like this:

for field in FieldSet:
    if len(FieldSet[field]) == 1:
        del(FieldSet[field])

但是收到错误RuntimeError:字典在执行期间改变大小。 (不要惊讶,因为这正是我在做的事情。)如果我必须敲定一些解决方法,这不是全部的,最终的,但是可以这样做吗?

But receive the error "RuntimeError: dictionary changed size during execution". (Not surprising, since that's what I'm doing.) It's not the be-all and end-all if I have to knock together some sort of workaround, but is it possible to do this?

推荐答案

迭代从 .keys() 。由于您已经收到了钥匙列表,因此您可以在调用之后更改字典而不受影响。

Iterate over the return value from .keys() instead. Since you get a list of keys back, it won't be affected by changing the dictionary after you've called it.

这篇关于从python中的字典中删除某些键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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