0

I have a string that is in the format of k1=v1,k2=v2 and so on. I want to return that k which has highest v.

I am trying to run below code but it does not seem to work -

s1 = "0=0.0,1=4.097520999795124e-05,2=0.0007278731184387373,3=0.339028551210803,4=0.33231086508575525,5=0.32789173537500504"
stats = dict(map(lambda x: x.split('='), s1.split(',')))
x = max(stats, key=stats.get)
print(x)

This prints 1 whereas the expected output is 3.

yatu
  • 86,083
  • 12
  • 84
  • 139
Regressor
  • 1,843
  • 4
  • 27
  • 67
  • 4
    remember your keys are strings (what str.split is going to return) not integers. 12 < 2 in string ordering. – erik258 Oct 28 '19 at 16:22
  • 1
    Duplicate to: https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary – Lenny Eing Oct 28 '19 at 16:31
  • Possible duplicate of [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) – Chris Oct 28 '19 at 21:29

1 Answers1

2

You could use max, with a key to consider only the second value in the key/value tuples. Also note that the values must be cast to float, since otherwise element's comparisson will be lexicographical:

from operator import itemgetter

max_val = max(((k,float(v)) for k,v in stats.items()), key=itemgetter(1))
print(max_val)
# ('3', 0.339028551210803)

print(max_val[0])
# 3
yatu
  • 86,083
  • 12
  • 84
  • 139