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

后端 未结 18 2866
半阙折子戏
半阙折子戏 2020-11-21 04:06

I have a list of dictionaries and want each item to be sorted by a specific value.

Take into consideration the list:

[{\'name\':\'Homer\', \'age\':39},         


        
18条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 04:57

    my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
    
    my_list.sort(lambda x,y : cmp(x['name'], y['name']))
    

    my_list will now be what you want.

    Or better:

    Since Python 2.4, there's a key argument is both more efficient and neater:

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

    ...the lambda is, IMO, easier to understand than operator.itemgetter, but your mileage may vary.

提交回复
热议问题