As from Python 3.2 it is recommended to use functools.cmp_to_key() which has been added to the standard library to do sorting the “old way” with comparators.

This is also easier to read than confusing lambdas and easier to extend when you have more than 2 variables that need to be compared.

In the example below we are sorting a list of dictionaries based on their weights and prices. We are sorting them by prioritizing smaller weights and higher prices in this example.

list = [
    {"weight":10, "price": 10},
    {"weight":5, "price":20},
    {"weight": 10, "price": 21}
]

def compare(left, right):
    if left['weight'] < right['weight']: #prioritize smaller weight
        return -1
    elif left['weight'] == right['weight']:
        if left['price'] > right['price']: #but prioritize bigger prices
            return -1
        elif left['price'] == right['price']:
            return 0
        else:
            return 1
    else:
        return 1

from functools import cmp_to_key
sorted_list = sorted(list, key=cmp_to_key(compare), reverse=False)
print(sorted_list)

Notice that you also easily add a reverse parameter to automatically sort in the reverse order. This is handy for programming contests.

You can also provide a formula instead of -1,0 and 1 as result when comparing the left hand side with the right hand side. For example:

list = [
    {"weight":10, "price": 10},
    {"weight":5, "price":20},
    {"weight": 10, "price": 21}
]


def compare(left, right):
    return (left["weight"]*left["price"] - right["weight"]*right["price"])

from functools import cmp_to_key
sorted_list = sorted(list, key=cmp_to_key(compare), reverse=False)
print(sorted_list)

This is just an example and the way that the sorting is being done is basically the weight multiplied by the price, which is the smallest combination of (weight,price) first. Anyway, hope that this snippet has been useful to you.

We have more useful python articles that you can check:

How To Open A File In Python

Python Logging To CSV With Log Rotation and CSV Headers

Python logging json formatter

If you would like to learn more Python check out this certificate course by Google: IT Automation with Python