pythonlistsorting

sort a list of dicts by x then by y


I want to sort this info(name, points, and time):

list = [
    {'name': 'JOHN', 'points': 30, 'time': '0:02:02'},
    {'name': 'MATT', 'points': 30, 'time': '0:02:00'},
    {'name': 'KARL', 'points': 50, 'time': '0:03:00'}
]

so, what I want is the list sorted first by points made, then by time played (in my example, matt go first because of his less time. any help?

I'm trying with this:

import operator
list.sort(key=operator.itemgetter('points', 'time'))

but got a TypeError: list indices must be integers, not str.


Solution

  • Your example works for me. I would advise you not to use list as a variable name, since it is a builtin type.

    You could try doing something like this also:

    list.sort(key=lambda item: (item['points'], item['time']))