如何按字母顺序和最高数字对列表中的字典进行排序
How to order a dictionary within a list by alphabetical order and highest number
我有一段基本的编码如下:
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"])
我已经整理好了,它会按字母顺序打印出人们的名字,但是,我现在需要代码工作,这样它会按字母顺序打印出名字,而且它只打印出最高分.
您的分数存储在三个单独的键中;使用 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 中选择),但是最高分数就像 [=15] =].
我有一段基本的编码如下:
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"])
我已经整理好了,它会按字母顺序打印出人们的名字,但是,我现在需要代码工作,这样它会按字母顺序打印出名字,而且它只打印出最高分.
您的分数存储在三个单独的键中;使用 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 中选择),但是最高分数就像 [=15] =].