Skip to content

Latest commit

 

History

History
34 lines (23 loc) · 756 Bytes

61.md

File metadata and controls

34 lines (23 loc) · 756 Bytes
rank vote view answer url
61 1413 541572 17 url

通过列表中字典的值对列表进行排序

我的到了一个字典的列表,我想对字典的值进行排序.

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

对name进行排序,应当是:

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

用key比用cmp更清晰明了:

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

或者其他人的建议:

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