Reputation: 83
UCI = {'A+': 4.0, 'A': 4.0,'A-': 3.7,
'B+': 3.3, 'B': 3.0,'B-': 2.7,
'C+': 2.3, 'C': 2.0,'C-': 1.7,
'D+': 1.3, 'D': 1.0,'D-': 0.7,
'F': 0.0}
def top(student_info : {(str,str)}) -> {str}:
name_set = set()
for x in sorted(student_info, key = lambda x: x[0][-1], reverse = True):
print(x)
top({('Alice','C'),('Bobby','B-'),('Carol','B-'),('David','D'),('Evelyn','C+')})
I want to sort this set by the key of their grade from the highest to the lowest. However, it does not give me the right order. What I got is:
('Bobby', 'B-')
('Evelyn', 'C+')
('Carol', 'B-')
('Alice', 'C')
('David', 'D')
Any help will be appreciated! Thank you
Upvotes: 0
Views: 90
Reputation: 37579
It's sorting correctly. You have it sorting by the last character in the first item in the tuple. The key
function is going to be fed individual elements, like ('Alice', 'C')
. So x[0][-1]
gets the first element ('Alice'
) and then takes the last character ('e'
). The output is in reverse order.
What you want is
lambda x: UCI[x[1]]
Upvotes: 1
Reputation: 132138
I think what you want is
>>> sorted(students, key = lambda x: UCI[x[1]], reverse=True)
[('Carol', 'B-'), ('Bobby', 'B-'), ('Evelyn', 'C+'), ('Alice', 'C'), ('David', 'D')]
You were never referencing UCI in your sorting.
In the lambda, x
is the tuple (name, grade) so x[0]
is name, and x[1]
is the grade. You want to sort by the numerical value of grade based on the lookup in UCI, so that would be UCI[x[1]]
Upvotes: 1