Worksheet: Sorting in Python
The method sort() sorts a list in place:
The function sorted(), on the other hand, leaves the original list unchanged, but returns a sorted list.
The parameter reverse=True inverts the sorting order.
Sorting Python dictionaries by their values
Suppose we have a dictionary of word counts, for example
If we try to sort it using the same formulation as for lists above, we get the dictionary keys in alphabetical order:
If we sort key/value pairs, we still get them in alphabetical order of the keys:
We need to change the way that sorted() looks at the items that it is sorting. In particular, we want to map each key/value pair to the value, as this is what sorted() should consider for sorting. To do this, we define a function that maps pairs to the second element, and hand it on to sorted() as the sorting key function:
To get the highest counts first, we do
We only need the function second_of_pair() in one place: as a sorting key for sorted(). For cases like these, Python has "nameless functions". We can write
to get the same result as the previous call to sorted(). Note that while the separate function definition of second_of_pair() had to use the "return" statement, the lambda formulation cannot use it.