18

My dict is like,

{'A':4,'B':10,'C':0,'D':87}

I want to find max value with its key and min value with its key.

Output will be like ,

max : 87 , key is D

min : 0 , key is C

I know how to get min and max values from dict. Is there is any way to get value and key in one statement?

max([i for i in dic.values()]) 
min([i for i in dic.values()])
2

3 Answers 3

59

You could use use max and min with dict.get:

maximum = max(mydict, key=mydict.get)  # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87
6
  • i dont think it will work,
    – Hackaholic
    Nov 11, 2014 at 18:36
  • 1
    @hackaholic Do explain why, I'd love to know. Nov 11, 2014 at 18:36
  • 1
    what if D has lowe value than A and C
    – Hackaholic
    Nov 11, 2014 at 18:36
  • 8
    You could also do key, value = max(mydict.iteritems(), key = lambda p: p[1]), since the question specifically mentions getting the key and value together. But it's rarely worth typing more code just to save dictionary lookups. Nov 11, 2014 at 18:53
  • 1
    Make sure your values are numbers and not strings or you will get wrong answers.
    – Noumenon
    May 8, 2017 at 21:41
14

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)
6

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])
1
  • 5
    This doesn't meet the specifications of the question. It is supposed to find the key with the highest value; not the greatest key and the greatest value. Nov 11, 2014 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.