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

后端 未结 18 2867
半阙折子戏
半阙折子戏 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 05:00

    If you want to sort the list by multiple keys, you can do the following:

    my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]
    sortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name']))
    

    It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).

提交回复
热议问题