11

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?

Community
  • 1
  • 1
user338413
  • 689
  • 2
  • 8
  • 20
  • I had a little bit of fun answering a similar question a while back ( http://stackoverflow.com/a/11732149/748858 ). I discussed sorting fairly in-depth so I'll leave a link here with the hopes that it will be helpful. – mgilson Aug 15 '12 at 13:59

3 Answers3

6

Use operator.itemgetter as the key:

sorted(teamlist, key=operator.itemgetter('rating'))
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Do you know if there is any advantage to using `operator.itemgetter` over the `lambda` key that I use in my answer? – Brendan Wood Aug 15 '12 at 14:03
  • Thanks, this did it. Much easier than the old way I tried before using lambda and maps. – user338413 Aug 15 '12 at 14:04
  • @BrendanWood -- Some people don't like `lambda`. Also, `operator.itemgetter` is *slightly* faster -- But, probably not enough to make it worth worrying about in common situations. – mgilson Aug 15 '12 at 14:08
  • @mgilson -- Thanks, I always like learning faster ways of doing things. – Brendan Wood Aug 15 '12 at 14:11
  • @BrendanWood they're equivalent, although `itemgetter` has the advantage when you want to sort by multiple keys (you can write `itemgetter(key1, key2, ...)`. I assume it's mainly there because Guido doesn't like lambdas. – ecatmur Aug 15 '12 at 14:11
4

You can use the sorted function with a sorting key referring to whichever field you wish.

teamlist_sorted = sorted(teamlist, key=lambda x: x['rating'])
Brendan Wood
  • 6,220
  • 3
  • 30
  • 28
1
from operator import itemgetter
newlist = sorted(team_list, key=itemgetter('rating')) 
NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53