[英]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.我有一个格式为k1=v1,k2=v2
的字符串,依此类推。 I want to return that k
which has highest v
.我想返回具有最高v
的k
。
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
.这打印1
而预期的 output 是3
。
You could use max
, with a key to consider only the second value in the key
/ value
tuples.您可以使用max
和一个键来仅考虑key
/ value
元组中的第二个值。 Also note that the values
must be cast to float
, since otherwise element's comparisson will be lexicographical:另请注意,必须将values
强制转换为float
,否则元素的比较将是字典顺序的:
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.然后根据相关问题使用itemgetter
来获取字典中最大值的键。
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.您的问题是 '4.097520999795124e-05' 在 lex 排序时的评估值高于 '0.339028551210803' 。
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.拿stats.keys()
,用一个真正的 int 替换每个列表理解,然后取该列表的最大值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.