python字典:如何获取具有特定值的所有键 [英] python dictionary: How to get all keys with specific values
问题描述
是否可以将字典中的所有键的值都超过阈值?
Is it possible to get all keys in a dictionary with values above a threshold?
一本字典的样子:
mydict = {(0,1,2):"16",(2,3,4):"19"}
例如,阈值可能是17
The Threshold could be 17 for example
推荐答案
当然可以.我们可以简单地写:
Of course it is possible. We can simply write:
[k for k,v in mydict.items() if float(v) >= 17]
或者在您使用python的情况下-2.7 ,您-喜欢
Or in the case you work with python-2.7, you - like @NoticeMeSenpai says - better use:
[k for k,v in mydict.iteritems() if float(v) >= 17]
这是列表理解.我们遍历mydict
词典中的键值对.接下来,将值v
转换为float(v)
,并检查该float是否大于或等于17.如果是这种情况,我们将键k
添加到列表中.
This is a list comprehension. We iterate through the key-value pairs in the mydict
dictionary. Next we convert the value v
into a float(v)
and check if that float is greater than or equal to 17. If that is the case, we add the key k
to the list.
对于给定的mydict
,它会生成:
For your given mydict
, this generates:
>>> [k for k,v in mydict.items() if float(v) >= 17]
[(2, 3, 4)]
因此包含满足以下条件的单键的列表:(2,3,4)
.
So a list containing the single key that satisfied the condition here: (2,3,4)
.
这篇关于python字典:如何获取具有特定值的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!