Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

mydict = {(0,1,2):"16",(2,3,4):"19"}

The Threshold could be 17 for example

like image 675
Varlor Avatar asked Jun 20 '17 22:06

Varlor


People also ask

How do I get all the values of a key in Python?

In Python to get all key-values pair from the dictionary, we can easily use the method dict. items(). This method helps the user to extract all keys and values from the dictionary and iterate the object with a for loop method.

Can we get a key from values in dictionary Python?

We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.

How do you get a specific value from a dictionary in Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.


1 Answers

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:

[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.

For your given mydict, this generates:

>>> [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).

like image 72
Willem Van Onsem Avatar answered Oct 13 '22 15:10

Willem Van Onsem