关于python:如何根据字典中的值对字典列表进行排序?

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

本问题已经有最佳答案,请猛点这里访问。

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

我正在编写一个python 3.2应用程序,我有一个包含以下内容的字典列表:

1
2
3
4
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 }]

我希望列表按分级键中的值排序。我怎样才能做到这一点?


使用operator.itemgetter作为键:

1
sorted(teamlist, key=operator.itemgetter('rating'))


您可以使用sorted函数,其中排序键指向您希望的任何字段。

1
teamlist_sorted = sorted(teamlist, key=lambda x: x['rating'])


1
2
from operator import itemgetter
newlist = sorted(team_list, key=itemgetter('rating'))