Python: sort an array of dictionaries with custom comparator?

后端 未结 8 1421

I have the following Python array of dictionaries:

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


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 10:49

    Just give pass to "key" an arbitrary function or callable object - it is what it takes. itemgetter happens to be one such function -- but it can work with any function you write - it just has to take a single parameter as input, and return an object that is directly compable to achieve the order you want.

    In this case:

    def key_func(item):
       return item["rank"] if item["rank"] != 0 else -100000
    
    sorted_master_list = sorted(myarr, key=key_func)
    

    (it can also be written as a lambda expression)

提交回复
热议问题