sorted() with key=
Sorting by a computed value rather than the item itself, and the difference between sorted() and .sort().
Overview
key is a function of one item
sorted(words, key=len)
key is called once per item and returns the value to sort on. Here len turns each word into its length, and the words come back shortest first. The items in the result are still the words; only the comparison changed.
Anything callable works: a builtin, a lambda, a named function.
sorted(people, key=lambda p: p[1]) # by the second element
sorted(rows, key=lambda r: r["score"]) # by a dict field
sorted_key.py
sorted_vs_sort.py
Worth knowing
key is a function of one item that returns the value to sort on.sorted() returns a new list; .sort() rearranges in place and returns None.key to sort by one field then another.