Photo by Mikael Kristenson on Unsplash

Sorted is one of the most used built-in functions. The basic sorted behavior is ascending, for example:

>>> fruits = {'apple': 5, 'orange': 7, 'banana': 3}
>>> sorted(fruits)
['apple', 'banana', 'orange']

Now, to reverse the sorting order, we set the reverse parameter to true:

>>> sorted(fruits, reverse=True)
['orange', 'banana', 'apple']

The default behavior of sorted is sorting using the first attribute (apple, orange, and banana).

Sorting by the second attribute (5, 7, and 3) requires passing an anonymous function:

>>> sorted(fruits, key=lambda x: x[-1])
['banana', 'apple', 'orange']
  • x[-1] means the last attribute, which is equivalent to x[1]
  • key = lambda x: x[-1] is equivalent to:
def key(x):
return x[-1]

Hope this helps.