Sorting a DictionaryΒΆ

Previously, you have used a dictionary to accumulate counts, such as the frequencies of letters or words in a text. For example, the following code counts the frequencies of different numbers in the list.

The dictionary’s keys are not sorted in any particular order. In fact, you may get a different order of output than someone else running the same code. We can force the results to be displayed in some fixed ordering, by sorting the keys.

With a dictionary that’s maintaining counts or some other kind of score, we might prefer to get the outputs sorted based on the count rather than based on the items. There are a couple ways to do that. The first is, I think, a little easier to understand. The second is the more standard idiom for python programmers; once you get used to it, it’s a lot easier to read.

Here’s the first way, using a lambda expression.

Here’s that same way of doing it, using a named function instead of a lambda expression that produces an anonymous function.

Most python programmers would never sort the items (the key, value pairs) from a dictionary. Instead, the standard idiom is to sort just the keys, based on their associated values. Because python lets you pass a function to the sorted parameter, you can pass a function that looks up the value associated with a key and causes that value to be written on the post-it notes that determine the sort order.

Here’s a version based on sorting the keys rather than the complete items, using a lambda expression.

And here’s a version of that using a named function.

Note

When we sort the keys, passing a function with key = lambda x: d[x] does not specify to sort the keys of a dictionary. The lists of keys are passed as the first parameter value in the invocation of sort. The key parameter provides a function that says how to sort them.

An experienced programmer would probably not even separate out the sorting step. And they might take advantage of the fact that when you pass a dictionary to something that is expecting a list, its the same as passing the list of keys.

Eventually, you will be able to read code like that above and immediately know what it’s doing. For now, when you come across something confusing, like line 11, try breaking it down. The function sorted is invoked. Its first parameter value is a dictionary, which really means the keys of the dictionary. The third parameter, the key function, decorates the dictionary key with a post-it note containing that key’s value in dictionary d. The last parameter, True, says to sort in reverse order.

Next Section - Breaking ties with stable sorting