我有一个基本的编码如下:
dict1 = [{"Name":"Ron","one":3,"two":6,"three":10}
,{"Name":"Mac","one":5,"two":8,"three":0}
,{"Name":"DUDE","one":16,"two":9,"three":2}]
print(dict1)
import operator
dict1.sort(key=operator.itemgetter("Name"))
print("\nStudents Alphabetised\n")
for pupil in dict1:
print ("StudentName",pupil["Name"],pupil["one"],pupil["two"],pupil["three"])
我已整理出来,所以它会按字母顺序打印出人们的名字,但是,我现在需要代码工作,这样就可以按字母顺序打印出名字,但也打印出最高的名字。得分。
答案 0 :(得分:4)
您的分数存储在三个单独的键中;使用max()
function选择最高的一个:
for pupil in dict1:
highest = max(pupil["one"], pupil["two"], pupil["three"])
print("StudentName", pupil["Name"], highest)
通过将所有分数存储在列表中而不是三个单独的键,您可以让您的生活更轻松:
dict1 = [
{"Name": "Ron", 'scores': [3, 6, 10]},
{"Name": "Mac", 'scores': [5, 8, 0]},
{"Name": "DUDE", 'scores': [16, 9, 2]},
]
然后,您仍然可以使用pupil['scores'][index]
(其中index
是一个整数,从0,1或2中选择)来处理各个分数,但最高分数就像max(pupil['scores'])
一样简单