繁体   English   中英

找出嵌套字典中的值的总和并返回最大的键

[英]find out sum of values in nested dictionary and return the largest key

my_dict = {"student1": {"subject1": 100,"subject2":80, "subject3": 70},
           "student2": {"subject1": 500,"subject2":30, "subject3": 600}}

需要找出哪个学生的总分最高?

您可以使用字典理解来获取每个学生的分数总和。 然后,您可以使用max()找到总分最高的学生:

data = {"student1": {"subject1": 100,"subject2":80, "subject3": 70},
           "student2": {"subject1": 500,"subject2":30, "subject3": 600}}

totals = {student_id: sum(scores.values()) for student_id, scores in data.items()}
print(totals) # Prints {'student1': 250, 'student2': 1130}.

# Each element in .items() is a tuple with the student id as the first element,
# and their score as the second element.
# The key argument has us find the tuple with the maximum score.
top_scorer, top_score = max(totals.items(), key=lambda x: x[1])
print(top_scorer) # Prints student2.
print(top_score) # Prints 1130.

计算两个学生的最高分如下:

x = [sum(my_dict[i].values()) for i in my_dict.keys()]

然后打印得分最高的学生的姓名,如下所示:

if x[0] > x[1]:
    print("Student 1 has highest marks: ", x[0])
else:
    print("Student 2 has highest marks: ", x[1])

做就是了:

max(my_dict, key=lambda x:sum(my_dict[x][i] for i in my_dict[x]))


'student2'

如果您要处理大量数据,最好将其转换为更有用的数据类型,例如

df= pd.DataFrame.from_dict(my_dict, orient = 'index')

那么你可以做

df.sum(axis=1).sort_values(ascending = False).index[0]

或者

sums = df.sum(axis=1)
max(sums.index, key = lambda x: sums[x])

暂无
暂无

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

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