Search code examples
pythondictionarylambdaconditional-statementsexpression

Get the key of the value satisfied the conditions in the dictionary


I have a dictionary as follows :

k = {'e': 8, 'f': 2, 'g': 3}

I want to give the condition: the value is smaller than the 5:

(For example: value < 5)

at the result:

the key of the max value under the condition

so I want to find the 'g'

My code was as follow:

k = {'e': 8, 'f': 2, 'g': 3}

t = {}

for i, j in k.items():
    if j < 5:
        t[i] = j

k_ = max(t, key=lambda x: t[x])

print(k_)

It is working but as you see, that is not simple.

I want to express simply using the expression, lambda and so on..

Could you teach me please


Solution

  • k = {'e': 8, 'f': 2, 'g': 3}
    
    t = {i: j for i, j in k.items() if j < 5}
    
    k_ = max(t, key=t.get)
    
    print(k_)