Python中怎样对一个字典dict按值排序?

How do I sort a list of dictionaries by values of the dictionary in Python?

I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This

[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

sorted by name, should become

[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

For completeness (as pointed out in comments by fitzgeraldsteele), add

reverse=True

to sort descending

newlist = sorted(l, key=itemgetter('name'), reverse=True)

原文:https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python

By Code问答

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 1 = 3