+3 votes
in Programming Languages by (73.8k points)
I have a dictionary with several elements. How can I find the key that has the max value or min value?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

You can use operator library as follows to find the key with the largest value or smallest value.

>>> import operator
>>> aa={'a':343,'b':23,'c':765,'d':78,'e':901}
>>> min(aa.items(), key=operator.itemgetter(1))[0]
'b'
>>> max(aa.items(), key=operator.itemgetter(1))[0]
'e'
>>> max(aa.items(), key=operator.itemgetter(1))
('e', 901)
 

 


...