繁体   English   中英

如何返回字典中与最大值对应的键?

[英]How to return the key corresponding to the maximum value in dictionary?

在这段代码中,我计算了每个学生的平均分数,并将其返回到字典中以创建带有二维数组的字典:

def bestAverage(inputDict):
    dic = {}
    for i in inputDict:
        if i[0] in dic.keys():
            dic[i[0]].append(int(i[1]))
        else:
            dic[i[0]] = [int(i[1])]
    totle_score = 0
    print(dic)
    for key, value, in dic.items():
        for c in value:
         totle_score += int(c)
        Q = len(value)
        avrage = totle_score / Q
        dic[key]= [avrage]
    print(dic)

结果:

{'Diane': [35.0], 'Bion': [95.0], 'Jack': [125.0]}

现在,如何返回平均分最高的名字?

dict = {'Diane': [35.0], 'Bion': [95.0], 'Jack': [125.0]}

highest_scorer = max(dict, key=dict.get)
highest_score = dict[highest_scorer]

参考https://docs.python.org/3/library/functions.html#max

您也可以尝试max(iterable) ,但我更喜欢使用max(iterable, *args)

max_score = max(d.values())[0]
name_max = [k for k,v in d.items() if v[0]==max_score]
import operator
max(dic.items(), key=operator.itemgetter(1))[0]

你也可以使用

max(dic, key=dic.get)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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