python字典:如何获取具有特定值的所有键

时间:2022-01-03 21:15:36

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

1 个解决方案

#1


14  

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 , 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. 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字典中的键值对。接下来,我们将值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)。

#1


14  

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 , 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. 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字典中的键值对。接下来,我们将值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)。