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

时间:2019-02-26 04:18:59

标签: python

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

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]}

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

3 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

max_score = max(d.values())[0]
name_max = [k for k,v in d.items() if v[0]==max_score]

答案 2 :(得分:-1)

import operator
max(dic.items(), key=operator.itemgetter(1))[0]

您也可以使用

max(dic, key=dic.get)