Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print highest value in dict with key [duplicate]

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()])
like image 496
Nishant Nawarkhede Avatar asked Nov 11 '14 18:11

Nishant Nawarkhede


People also ask

How do you find the highest value in a dictionary?

Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.

How do you find the second highest value in a dictionary?

We can find the second largest value in a dictionary by sorting the values of the dictionaries and then retrieving the second last element from the sorted list.


2 Answers

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)
like image 100
holdenweb Avatar answered Oct 17 '22 07:10

holdenweb


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
like image 35
anon582847382 Avatar answered Oct 17 '22 07:10

anon582847382