如何使用循环获取字典键? [关闭]

问题描述 投票:-3回答:1
scores= {'Tim':(99,89,80,85), 'Eric':(100,95,97,75), "Mary":(80,95,85,98), "Joy":(75,80,90,95)}

它显示{数学,英语,中文和自然科学的学生等级]

我只知道如何使用循环找到数学的最高分。

但是如何使用循环在数学中获得最高分(100)的名字叫“ Eric”?

python loops dictionary
1个回答
1
投票

方法1--使用For循环

top_scorer = ""
top_score = 0
for name, vals in scores.items():
  if vals[0] > top_score:
    top_scorer, top_score = name, vals[0]

print(top_scorer)

方法2-使用比较键

print(max(scores, key = lambda kv: kv[1][0]))

其他选项结帐 tUsing max on dictionaries

输出(两种方法都相同)

Eric
Eric
© www.soinside.com 2019 - 2024. All rights reserved.