Python: sort an array of dictionaries with custom comparator?

后端 未结 8 1235

I have the following Python array of dictionaries:

myarr = [ { \'name\': \'Richard\', \'rank\': 1 },
{ \'name\': \'Reuben\', \'rank\': 4 },
{ \'name\': \'Reece\'         


        
8条回答
  •  梦谈多话
    2021-02-08 11:00

    You can use function in key param:

    for ass sorting:

    sorted_master_list = sorted(myarr, key=lambda x: x.get('rank'))
    

    or to desc:

    sorted_master_list = sorted(myarr, key=lambda x: -x.get('rank'))
    

    Also you can read about sorted function here http://wiki.python.org/moin/HowTo/Sorting

提交回复
热议问题