I have a dictionary with several elements. How can I find the key that has the max value or min value?

+1 vote

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)