Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:2'},
    {'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.

like image 889
dobleseis Avatar asked May 10 '11 02:05

dobleseis


1 Answers

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']))
like image 193
Ponkadoodle Avatar answered Sep 23 '22 07:09

Ponkadoodle