How to multisort list of dictionaries in Python?

This question already has an answer here:

  • How do I sort a list of dictionaries by values of the dictionary in Python? 17 answers

  • You can use those two values of those two keys as representative of the current dictionary during the sorting's comparison.

    sorted(test, key=lambda x: (-d['ratio'], d['delta']))
    

    will sort them based on ratio 's descending order first and if the values are equal, then delta 's ascending order.


    Here, we negate the value of d['ratio'] , because by default, sorted does sort in ascending order. As we want the largest value of ratio to be at the beginning, we negate the value so that the biggest ratio will be treated as the smallest ratio . (For example out of 1, 10, and 100, after negating the values, -100 will be the smallest).

    We want Python to use both the ratio and delta . So, we return the values of them in a tuple. When Python compares two dictionaries, it calls the key function with the dictionary objects as parameters and get two tuples and they will be compared to determine the smaller of the two. First, it compares the first elements of the tuples, if they are same, then the second elements will be compared.


    简单如下:

    from operator import itemgetter
    
    >>> result = sorted(test, key=itemgetter('-ratio'))
    >>> result = sorted(result, key=itemgetter('delta'))
    
    链接地址: http://www.djcxy.com/p/70770.html

    上一篇: 如何根据价值对字典词典列表进行排序

    下一篇: 如何在Python中多列出字典列表?