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

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

    Sometimes we need to use lower(). For example,

    lists = [{'name':'Homer', 'age':39},
      {'name':'Bart', 'age':10},
      {'name':'abby', 'age':9}]
    
    lists = sorted(lists, key=lambda k: k['name'])
    print(lists)
    # [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]
    
    lists = sorted(lists, key=lambda k: k['name'].lower())
    print(lists)
    # [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
    

提交回复
热议问题