简体   繁体   English

从python中的字典中删除某些键

[英]Remove certain keys from a dictionary in 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])

But receive the error "RuntimeError: dictionary changed size during execution". 但收到错误“RuntimeError:字典在执行期间改变了大小”。 (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? (这并不奇怪,因为那就是我正在做的事情。)如果我不得不采取某种解决方法,那不是全部和最终的结果,但是有可能做到这一点吗?

Iterate over the return value from .keys() instead. 迭代来自.keys()的返回值。 Since you get a list of keys back, it won't be affected by changing the dictionary after you've called it. 由于您获得了一个键列表,因此在调用它之后更改字典不会影响它。

A sometimes-preferable alternative to changing FieldSet in place is sometimes (depending on the amount of alterations performed) to build a new one and bind it to the existing name: 有时候更好地替换FieldSet的替代方法有时(取决于执行的更改量)来构建新的并将其绑定到现有名称:

FieldSet = dict((k, v) for k, v in FieldSet.iteritems()
                if len(v) != 1)

There is the pop method. 有pop方法。 It removes the element that a key calls. 它删除了键调用的元素。 With respect to your example this looks like: 关于您的示例,这看起来像:

for field in FieldSet.keys():
    if len(FieldSet[field]) == 1:
        FieldSet.pop(field)

This is in python 3.2, but I'm not sure if it's a new feature: http://docs.python.org/dev/library/stdtypes.html#dict.pop 这是在python 3.2中,但我不确定它是否是一个新功能: http//docs.python.org/dev/library/stdtypes.html#dict.pop

Just tried it and it works as advertised. 刚尝试过,它就像宣传的那样有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM