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
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.
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.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With