Python - 添加到字典,找到最大的值

时间:2017-07-25 03:12:14

标签: python dictionary

我带了两个元组列表,做了一些计算并创建了一个字典,或者至少尝试过,这样我就可以找到百分比最大的字符。

    dict_original = dict(original_list)
    for c, p in new_list:
        if c in dict_original and dict_original[c] < p:
            diff = p - dict_original[c]
            output = {c:round(diff,3)}
            print output

我得到的输出是这样的:

{'o': 0.026}
{'x': 0.046}
{'t': 0.037}
{'/': 0.038}
{'p': 0.037}
{'s': 0.038}

我想要的只是百分比最大的角色; &#39; x&#39;,在这种情况下。到目前为止,我使用max未成功。 我知道,我的输出似乎是一堆字典,这就是我在这里寻求帮助的原因。

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以传递max key参数:

bar = max(foo, key=foo.get)

这将为您提供具有最大价值的密钥。

答案 1 :(得分:1)

如果没有看到您的数据,很难为您提供适当的指导。

您没有创建所有结果的新字典,只是每个结果被丢弃的字典。您可以使用词典理解来创建完整的词典,例如这相当于你的for循环:

do = dict_original
output = {c: round(p-do[c], 3) for c, p in new_list if do.get(c, float('inf')) < p}

要获得此dict的最大值,请按@batman指出:

max(output, key=output.get)

会返回'x'