pythonlistdictionaryfilter

How to get all keys with specific values of a python dictionary


Is it possible to get all keys in a dictionary with values above a threshold?

A dictionary could look like:

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

The threshold could be 17 for example.


Solution

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