1

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.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Joao
  • 53
  • 4
  • 1
    Can you show exactly what your output should look like? – Anand S Kumar Oct 27 '15 at 09:51
  • ' [{'three': 10, 'Name': 'Ron', 'two': 6, 'one': 3}, {'three': 0, 'Name': 'Mac', 'two': 8, 'one': 5}, {'three': 2, 'Name': 'DUDE', 'two': 9, 'one': 16}] Students Alphabetised Student Name DUDE 16 9 2 Student Name Mac 5 8 0 Student Name Ron 3 6 10 ' – Joao Oct 27 '15 at 09:52
  • I mean't, include in queston what your expected output looks like. – Anand S Kumar Oct 27 '15 at 09:56

1 Answers1

4

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343