简体   繁体   English

Python3:通过理解从字典中有条件地提取键

[英]Python3: Conditional extraction of keys from a dictionary with comprehension

I need to extract those keys of a dictionary whose values pass a certain condition. 我需要提取其值超过某个条件的字典的那些键。 Basically, I want to do this, only in a shorter, more pythony way: 基本上,我想这样做,只是以更短,更pythony的方式:

keys=[]
for key in dict:
    if dict[key]==True:
        keys.append(key)

This was my original idea, but it raises a ValueError: 这是我最初的想法,但它引发了一个ValueError:

[key for (key,val) in map if val==True]

I came up with this for the moment, but I can't help feeling it's not very nice: 我暂时想出了这个,但我不禁觉得它不是很好:

[key for key in map.keys() if map[key]==True]

Is there a less messy way to it? 是否有一个不那么混乱的方式呢? Perhaps something obvious that I'm clearly missing? 也许显而易见的是我明显失踪了?

Thanks! 谢谢!

Here is a way to get the keys with true values that is a lot shorter and cleaner than a comprehension (not that comprehensions are bad though): 这里有一种方法可以获得具有真正值的键,这些值比理解更短更清晰(虽然理解力不好):

>>> dct = {0:False, 1:True, 2:False, 3:True}
>>> list(filter(dct.get, dct))
[1, 3]
>>>

Use dict.items() 使用dict.items()

[key for key, val in dct.items() if val]

If you want to take only the keys with True values, rather than any true-ish value, you can use an equality check: 如果您只想使用True值而不是任何true-ish值,您可以使用相等性检查:

[key for key, val in dct.items() if val==True]

It is noted in PEP8 though, that one shouldn't compare boolean values using == - so don't use it unless you absolutely need to. 但是在PEP8中注意到,不应该使用==比较布尔值,所以除非你绝对需要,否则不要使用它。

Also, please don't name variables dict or map (even if it's for demonstration purposes only) because they shadow the bulitins. 另外,请不要将变量命名为dictmap (即使它仅用于演示目的),因为它们会影响bulitins。

Iterating over a mapping yields only keys. 迭代映射只产生键。 Use map.items() instead. 请改用map.items()

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

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