Joao
Joao

Reputation: 53

How to order a dictionary within a list by alphabetical order and highest number

I have a basic piece of coding which follows:

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

I have sorted out it so it will print out people's names in alphabetical order, however, I now need the code working so it would print out the names in alphabetical order, but also so it prints out the highest score only.

Upvotes: 1

Views: 81

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124988

Your scores are stored in three separate keys; use the max() function to pick the highest one:

for pupil in dict1:
    highest = max(pupil["one"], pupil["two"], pupil["three"])
    print("StudentName", pupil["Name"], highest)

You could make your life easier by storing all the scores in a list, rather than three separate keys:

dict1 = [
    {"Name": "Ron", 'scores': [3, 6, 10]},
    {"Name": "Mac", 'scores': [5, 8, 0]},
    {"Name": "DUDE", 'scores': [16, 9, 2]},
]

You can then still address individual scores with pupil['scores'][index] (where index is an integer, pick from 0, 1 or 2), but the highest score is then as simple as max(pupil['scores']).

Upvotes: 4

Related Questions