Return maximum value from list of tuples

Viewed 900

If I have the following nested list in parenthesis:

[('Frank', '8'), ('Peter', '10'), ('Spank', '0')]

What can I do to return the maximum value and corresponding name from the list?

Desired output:

('Peter', '10')

I have tried max(list, key=itemgetter(1))[0] with no luck.

3 Answers

Just convert the key field to int

data = [('Frank', '8'), ('Peter', '10'), ('Spank', '0')]
mx = max(data, key=lambda e: int(e[1]))
print(mx)

output

('Peter', '10')

Try with this function. It takes as input a list with the same format than in your example and returns the element with the greatest number.

def findMax (names): #names = [('Frank', '8'), ('Peter', '10'), ('Spank', '0')]
numbers = [] #list for storing the numbers
for i in names:
    numbers.append (int (i [1]))

return names [numbers.index (max (numbers))] #search the max value in numbers and print the names element with the same index

If you want to use operator.itemgetter, you should probably convert the second item of each tuple to int:

>>> from operator import itemgetter
>>> lst = [('Frank', '8'), ('Peter', '10'), ('Spank', '0')]
>>> max(((k, int(v)) for k, v in lst), key=itemgetter(1))
('Peter', 10)

Strings do lexographical ordering for comparisons by default, so doing the int conversion is necessary in this case. You can test this out by doing '8' > '10' and seeing that it gives back True. You can read the docs for more information.

Related