簡體   English   中英

如何按字母順序和最高編號對列表中的字典進行排序

[英]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()函數選擇最高的一個:

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'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM