简体   繁体   中英

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 .

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

First, convert your string dictionary to one keyed on integers with floats as the values.

s1 = "0=0.0,1=4.097520999795124e-05,2=0.0007278731184387373,3=0.339028551210803,4=0.33231086508575525,5=0.32789173537500504"

d = dict(pair.split('=') for pair in s1.split(','))
d = dict(zip([int(k) for k in d], [float(v) for v in d.values()]))
>>> d
{0: 0.0,
 1: 4.097520999795124e-05,
 2: 0.0007278731184387373,
 3: 0.339028551210803,
 4: 0.33231086508575525,
 5: 0.32789173537500504}

Then use itemgetter per the related question to get the key for the max value in a dictionary.

import operator

>>> max(d.items(), key=operator.itemgetter(1))[0]
3

Your method works as well once the dictionary is in the correct format:

>>> max(d, key=d.get)
3

Your issue is that '4.097520999795124e-05' evaluates higher than '0.339028551210803' when lex sorted.

This seems to work for me:

>>> stats = { "1": "a", "2": "b", "3": "c"}
>>> max([ int(i) for i in stats.keys()])
3

Take stats.keys() , replace each with a true int with a list comprehension, and then take the max of that list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM