[英]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.