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

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

    Let's say I have a dictionary D with the elements below. To sort, just use the key argument in sorted to pass a custom function as below:

    D = {'eggs': 3, 'ham': 1, 'spam': 2}
    def get_count(tuple):
        return tuple[1]
    
    sorted(D.items(), key = get_count, reverse=True)
    # Or
    sorted(D.items(), key = lambda x: x[1], reverse=True)  # Avoiding get_count function call
    

    Check this out.

提交回复
热议问题