Regressor
Regressor

Reputation: 1973

How to get a key with highest value from a dictionary that is created from a string?

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.

Upvotes: 0

Views: 60

Answers (1)

yatu
yatu

Reputation: 88305

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

Upvotes: 2

Related Questions