21

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

mgc
  • 4,750
  • 1
  • 22
  • 36
Varlor
  • 1,271
  • 2
  • 15
  • 44

1 Answers1

40

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:

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

Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485