Learner
Learner

Reputation: 493

Python - Finding max of

I am trying to find maximum value of a dictionary containing list using second element in the list.

Here is an example.

data = {0: [6.6, 0.19920350542916282],
 1: [0.31000000000000005, 0.13792538097003],
 2: [1.55, 0.2935644431995964],
 3: [12.5, 0.2935644431995964]}

max(data.items(), key=lambda x:x[1][1])

output will be (2, [1.55, 0.2935644431995964])

However I want to have the output as (3, [12.5, 0.2935644431995964]})

i.e. when two values are same, then again look at the first element of the list of those values and pick up the one that have maximum.

Upvotes: 0

Views: 49

Answers (2)

Alex Z
Alex Z

Reputation: 76

This should work:

data = {0: [6.6, 0.19920350542916282],
 1: [0.31000000000000005, 0.13792538097003],
 2: [1.55, 0.2935644431995964],
 3: [12.5, 0.2935644431995964]}

max(data.items(), key=lambda x:(x[1][1],x[1][0]))

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

when two values are same, then again look at the first element of the list of those values and pick up the one that have maximum

Then use a (x[1][1], x[1][0]) tuple as key:

>>> max(data.items(), key=lambda x:(x[1][1], x[1][0]))
(3, [12.5, 0.2935644431995964])

Upvotes: 1

Related Questions