Given a histogram as a dictionary, what is the most pythonic, “batteries included” way of sorting a list which only has elements from the dictionary, by the frequencies defined in that dictionary?
The keys of the dictionary (and implicitly the values in the list) are strings, and the frequencies are stored as integers.
I am interested only in the python2 solution, but you’re welcome to write a python solution as well, so others can benefit from it too (in the future).
This also has the benefit of sorting elements not in the dict as if it was in the dict with a value of 0, instead of just raising a KeyError
The
sorted()function has an optional argument ‘key’. This argument specifies a function of one argument that is used to extract a comparison key from each list element. This comparison key is used to determine ordering between elements.