Newbie: finding the key/index of the min/max element

Jimmy Retzlaff jimmy at retzlaff.com
Tue Apr 30 16:54:25 EDT 2002


Benjamin Han [mailto:bhan at andrew.cmu.edu] asked:
> how do you find the key/index of the max/min element in a
sequence/map?

In Python tuples are compared element-wise from first to last. So, e.g.:

>>> min((1, 2, 3), (1, 3, 2))
(1, 2, 3)

So what you need is to represent your dictionary as a list of tuples
with the values first and keys second. Here is one way to do that in
recent versions of Python:

>>> d = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5}
>>> invertedList = zip(d.values(), d.keys())
>>> invertedList
[(4, 'four'), (3, 'three'), (5, 'five'), (2, 'two'), (1, 'one')]

Then min/max can operate on that list:

>>> min(invertedList)
(1, 'one')
>>> max(invertedList)[1]
'five'


Jimmy





More information about the Python-list mailing list