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

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

    import operator
    

    To sort the list of dictionaries by key='name':

    list_of_dicts.sort(key=operator.itemgetter('name'))
    

    To sort the list of dictionaries by key='age':

    list_of_dicts.sort(key=operator.itemgetter('age'))
    

提交回复
热议问题