如何在 Python 中过滤字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4484690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:57:26  来源:igfitidea点击:

How to filter a dictionary in Python?

pythondictionary

提问by user426795

d = {'foo': 'x',
     'bar': 'y',
     'zoo': 'None',
     'foobar': 'None'}

I want to filter all the items whose value is 'None'and update the fooand baritems with a particular value. I tried:

我想过滤其值为 的所有项目并使用特定值'None'更新foobar项目。我试过:

for i in x.items():
   ....:    if i[i] == 'None':
   ....:        x.pop(i[0])
   ....:    else:
   ....:        x.update({i[0]:'updated'}) 

But it is not working.

但它不起作用。

采纳答案by khachik

It is not clear what is 'None'in the dictionary you posted. If it is a string, you can use the following:

不清楚'None'你贴的字典里有什么。如果是字符串,则可以使用以下内容:

dict((k, 'updated') for k, v in d.iteritems() if v != 'None')

If it is None, just replace the checking, for example:

如果是None,只需替换检查,例如:

dict((k, 'updated') for k, v in d.iteritems() if v is None)

回答by SilentGhost

it's not clear where you're getting your 'updated'value from, but in general it would look like this:

目前尚不清楚您'updated'从哪里获得价值,但总的来说,它看起来像这样:

{i: 'updated' for i, j in d.items() if j != 'None'}

in python2.7 or newer.

在 python2.7 或更新版本中。

回答by Rosh Oxymoron

new_d = dict((k, 'updated') for k, v in d.iteritems() if k != 'None')

回答by ismail

Something like this should work

这样的事情应该工作

>>> for x in [x for x in d.keys() if d[x] == 'None']:
        d.pop(x)

回答by Woody1193

You could try writing a general filter function:

您可以尝试编写一个通用过滤器函数:

def filter(dict, by_key = lambda x: True, by_value = lambda x: True):
    for k, v in dict.items():
        if (by_key(k) and by_value(v)):
            yield (k, v)

or

或者

def filter(dict, by_key = lambda x: True, by_value = lambda x: True):
    return dict((k, v) for k, v in dict.items() if by_key(k) and by_value(v))

and then you can do this:

然后你可以这样做:

new_d = dict(filter(d, by_key = lambda k: k != 'None'))

Note that this was written to be compatible with Python 3. Mileage may vary.

请注意,这是为了与 Python 3 兼容而编写的。里程可能会有所不同。

The cool thing about this is that it allows you to pass arbitrary lambdas in to filter instead of hard-coding a particular condition. Plus, it's not any slower than any of the other solutions here. Furthermore, if you use the first solution I provided then you can iterate over the results.

很酷的一点是,它允许您将任意 lambda 传入过滤器,而不是对特定条件进行硬编码。另外,它并不比这里的任何其他解决方案慢。此外,如果您使用我提供的第一个解决方案,那么您可以迭代结果。