I have a python dictionary:
dic={'a':'17','b':'9','c':'11'}
I want to find the lowest value in this dictionary and show the KEY name of that value
in the example above, I want the name : b
I have a python dictionary:
dic={'a':'17','b':'9','c':'11'}
I want to find the lowest value in this dictionary and show the KEY name of that value
in the example above, I want the name : b
This will do:
dic={'a':'17','b':'9','c':'11'}
min(dic.items(), key=lambda item: int(item[1]))[0]
Result:
b
This works by taking all the "items", which are the key-value pairs:
[('a', '17'), ('c', '11'), ('b', '9')]
We then use the min()
function to find the one with the minimum value:
('b', '9')
The items are compared based on the int()
value of the second item in each tuple by the key
function:
lambda item: int(item[1])
Once we have that item ('b', '9')
, we then get the key (the first item in that tuple).
k = {'a':'17', 'b':'9', 'c':'11'}
print sorted(k, key=lambda x:int(k[x]))[0]
Output: b
or
print min(k, key=lambda x:int(k.get(x)))