简体   繁体   English

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

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

In this code I calculated the average score for each student and return it in a dictionary to create a dictionary with a two-dimensional array: 在这段代码中,我计算了每个学生的平均分数,并将其返回到字典中以创建带有二维数组的字典:

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)

OUTCOME: 结果:

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

NOW, how to return the name with the highest average score? 现在,如何返回平均分最高的名字?

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

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

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

You can also try max(iterable) , but I prefer using max(iterable, *args) . 您也可以尝试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]

you can also use 你也可以使用

max(dic, key=dic.get)

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

相关问题 密钥对应python字典中的最大值 - key corresponding to maximum value in python dictionary 如何使用max() function在dictionary of dictionary中找到最大值对应的key? - How to find the key corresponding to the maximum value in a dictionary of dictionary using max() function? 在嵌套字典中查找最大值并返回键 - Find Maximum Value in Nested Dictionary and return Key 如何以最有效的方式获取字典列表中最大值的对应键? - how to get the corresponding key for the maximum value in dictionary list in the most effecient way? 如何删除值,但将相应的键保留在字典中? - How to remove a value but keep the corresponding key in a dictionary? 返回字典中第三个值最小的元组对应的键 - Return key corresponding to the tuple with smallest third value from dictionary 如果字典中的值在 dataframe 中,则返回特定的对应键 - If value from dictionary is in dataframe, return specific corresponding key 根据 Python 中的条件返回字典中最大值的键 - Return the key of the maximum value in a dictionary base on criteria in Python 如何在字典中获取匹配的 substring 键并在 Python 上返回相应的值? - How to get match substring key in dictionary and return corresponding values on Python? 如何将每个字典值插入到对应键之后的列表中? - How to Insert Each Dictionary Value into a List After the Corresponding Key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM