-1
10
John Seen 3.7
Bill Stark 2.06
Jack Connor 3.47
Drake Mason 3.05
Bill Callum 2.83
Emma Jake 3.65
William Damian 3.33
James Charlie 3.56
Oscar Rhys 3.78
George Reece 2.52

So if there are same "GPA" numbers (value) it should sort it by key (descending).

Following code sorts by value then sorts by key, but ascending

n = int(input())
grades = {}
result = ''
for i in range(n):
    student = input().split()
    grades[student[0] + ' ' + student[1]] = eval(student[2])

sorted_d = sorted(grades.items(), key=lambda x: (-x[1], x[0]))
for i in sorted_d:
    print(str(i[0]) + " - " + str(i[1]))
smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    Please make your data a reproducible example: `dat = list[ ('John Seen',3.7), ('Bill Stark',2.06)...]` – smci Nov 17 '18 at 03:58

1 Answers1

0

There are several misunderstandings in your code:

  • You chose a dict grades with key (student name) and value (GPA/grade)
  • Bad choice. You can't directly "sort" the tuples of (key, value) of a dictionary. So dict is the wrong choice.
  • Instead you wanted the data to be a list of lists/tuples of (student,grade)
  • So you shouldn't have used a dict for grades, you should use a list. (However since it's now a list of (student,grade) tuples, so call it e.g. sg or student_grades or dat or something).
  • Then your sort function will be pretty simple. If only you didn't need ascending order on col 1, but descending order on col 0, you could do l.sort(key=operator.itemgetter(1,2)). But you need different orders, so that forces you to use a custom sort(cmp=...) See e.g. this

I leave it to you to refactor your code. Looks like a fairly simple exercise once you decompose it right. The moral of the story is think carefully about your choice of data structure(s) for the task you need to do: the right choice will make things simple; the wrong choice will create problems, then you need to revisit your initial assumptions and consider the alternatives.

smci
  • 32,567
  • 20
  • 113
  • 146
  • @slider: I don't know for sure that it's a homework exercise, but it sure looks like one. I think giving hints and explaining principles is the best way to respond. (And if the OP does subsequently post code with a specific issue, can help them with that. But not give the full code solution upfront.) – smci Nov 17 '18 at 05:25