简体   繁体   中英

Python: complex sort of list of dictionaries

I have a list of dictionaries whose elements must be sorted according to a rather complex criterion. Please consider this typical element:

{
    'key1': True,                 # always boolean
    'key2': False,                # always boolean
    'key3': 23,                   # always int
    'key4': 1613.34,              # always float
    'key5': 'Some string',        # always str
    'key6': 'Some other string',  # always str
}

Suppose the desired sort order is: key1 ASC, key2 DESC, key3 ASC, key4 DESC, key5 ASC, key6 DESC .

I know I could do something like that:

my_sorted_list = sorted(my_list, key=lambda my_dict: (
    my_dict['key1'],
    -my_dict['key2'],
    my_dict['key3'],
    -my_dict['key4'],
    my_dict['key5'],
    tuple(-ord(c) for c in my_dict['key6'])     # is that really the way of doing it? :-| 
))

But that last expression seems very ugly and hacky (and perhaps inefficient) to me. Is there a cleanest way of performing the same classification?

Depending on how time-critical this action is, it might be better just to conduct the various sorts in sequence. So given a sort_control list with tuples of (field,order) you could sort multiple times to achieve the correct ordering:

from operator import itemgetter


def sort_list(in_list, sort_control):
    out_list = in_list.copy()
    for field, fwd in reversed(sort_control):
         out_list.sort(key=itemgetter(field), reverse = not fwd)
    return out_list

my_sorted_list = sort_list(my_list, [('key1',True), ('key2',False), ('key3',True), ('key4',False), ('key5',True), ('key6',False)])

One way is to implement a comparison function. Compared to the other response it has the benefit of only running a single call to sort/sorted. I do not know if it is faster or slower.

from functools import cmp_to_key

def keyorder(sort_control):
    def compare(a, b): # Custom comparison function to return
        for field, fwd in sort_control:
            comparison = (a[field] > b[field]) - (a[field] < b[field]) # 1 if a>b, 0 if a==b, -1 if a < b
            if comparison:
                if not fwd:
                    comparison = -comparison
                break
        return comparison
    return cmp_to_key(compare) # Create key from comparison function

    my_sorted_list = sorted(my_list, key=keyorder([('key1',True), ('key2',False), ('key3',True), ('key4',False), ('key5',True), ('key6',False)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM