0

students_grade is a list that contains tuples, each having a student name and a grade, both in a string. For example:

students_grade = [('jon','88'), ('bran', '100'), ('arya','93'), ('dan', '88')]

The goal is to create a new list with the same tuples ordered by the grades:

[('jon','88'), ('dan', '88',' ('arya','93'),('bran','100')]

Tried solving it using a dictionary, however I noticed that '100' < '93' returns True, so I tried sorting the dictionary by int(values), however got TypeError.

dic = {}
for i in students_grades:
    dic[i[0]] = i[1]
sorted_keys = sorted(dic.keys(), key = int(dic.get), reverse=True)

without the int(dic.get) it works fine. Why does it fail?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jonathan
  • 69
  • 4
  • Because you're trying to convert a dictionary instance method to an integer. Presumably you meant something like `key = lambda k: int(dic.get(k))`. The `key` argument must be a callable that accepts a single argument. – jonrsharpe May 16 '17 at 21:20

1 Answers1

1

There's no concept of order for a normal dictionary, and anyway you don't need it for sorting the list. Try this:

x = [('jon', '88'), ('bran', '100'), ('arya', '93'), ('dan', '88')]
sorted(x, key=lambda pair: int(pair[1]))
=>  [('jon', '88'), ('dan', '88'), ('arya', '93'), ('bran', '100')]
Óscar López
  • 232,561
  • 37
  • 312
  • 386