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

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

    You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.

    You could do it this way:

    def mykey(adict): return adict['name']
    x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]
    sorted(x, key=mykey)
    

    But the standard library contains a generic routine for getting items of arbitrary objects: itemgetter. So try this instead:

    from operator import itemgetter
    x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]
    sorted(x, key=itemgetter('name'))
    

提交回复
热议问题