Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a list of dictionaries by a value in the dictionary? [duplicate]

Possible Duplicate:
In Python how do I sort a list of dictionaries by values of the dictionary?

I'm writing a Python 3.2 app and I have a list of dictionaries containing the following:

teamlist = [{ "name":"Bears", "wins":10, "losses":3, "rating":75.00 },
            { "name":"Chargers", "wins":4, "losses":8, "rating":46.55 },
            { "name":"Dolphins", "wins":3, "losses":9, "rating":41.75 },
            { "name":"Patriots", "wins":9, "losses":3, "rating": 71.48 }]

I want the list to be sorted by the values in the rating key. How do I accomplish this?

like image 589
user338413 Avatar asked Aug 15 '12 13:08

user338413


1 Answers

Use operator.itemgetter as the key:

sorted(teamlist, key=operator.itemgetter('rating'))
like image 143
ecatmur Avatar answered Sep 29 '22 09:09

ecatmur