Sorted Key Function

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.

--

--

--

Reject the null hypothesis

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Angular vs Vue: Why Should You Choose One Over the Other?

Angular vs Vue: Why Should You Choose One Over the Other?

WebAssembly -Part II.b | Golang with WASM

AMA with MAK, 25th Sep, 2PM UTC

Note that the py-earth package is only compatible with Python 3.6 or below at the time of writing.

1.JavaScript Try…Catch

How To Post And Fetch Data Using React-query

Build Your Own Spotify Player with React Native

CS 373 Fall 2021 Blog #8: Ryan Gahagan

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mansoor Aldosari

Mansoor Aldosari

Reject the null hypothesis

More from Medium

Difference Between For and While Functions in Python Programming Language

Namespaces and Scope in Python

5 Python Tricks That Will Make Your Code Better

Explain Function in Python