[英]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? 是否可以使字典中的所有键的值超过阈值?
a dicitonary could look like: dicitonary可能看起来像:
mydict = {(0,1,2):"16",(2,3,4):"19"}
The Threshold could be 17 for example 例如,阈值可以是17
Of course it is possible. 当然有可能。 We can simply write:
我们可以简单地写:
[k for k,v in mydict.items() if float(v) >= 17]
Or in the case you work with python-2.7 , you - like @NoticeMeSenpai says - better use: 或者在你使用python-2.7的情况下,你 - 就像@NoticeMeSenpai所说 - 更好地使用:
[k for k,v in mydict.iteritems() if float(v) >= 17]
This is a list comprehension . 这是列表理解 。 We iterate through the key-value pairs in the
mydict
dictionary. 我们遍历
mydict
字典中的mydict
对。 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. 接下来,我们将值
v
转换为float(v)
并检查该float是否大于或等于17.如果是这种情况,我们将键k
添加到列表中。
For your given mydict
, this generates: 对于你给定的
mydict
,这会产生:
>>> [k for k,v in mydict.items() if float(v) >= 17]
[(2, 3, 4)]
So a list containing the single key that satisfied the condition here: (2,3,4)
. 所以包含满足条件的单个键的列表:
(2,3,4)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.