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

后端 未结 18 2817
半阙折子戏
半阙折子戏 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:59

    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)
    

提交回复
热议问题