13.5. Defining a function as a parameter

In Section 11.6 we have seen an example of a function that can take another function as a parameter. This is a general mechanism in Python. Another example is the sort() function. This function can take a comparison function as a parameter.

def numeric_compare(x, y):
   if x>y:
      return 1
   elif x==y:
      return 0
   else: # x<y
      return -1

>>> a = [5, 1, 10, 2]
>>> a.sort(numeric_compare)
>>> print a
[1, 2, 5, 10]

Exercise 13.1. Sorting a dictionary by its values

Let's say that we have a dictionary of the words occurring in a file associated with their number of occurrences. How would you print this dictionary by descending occurrences? You have to define a function freq_compare which takes as its two parameters the key of the entries that you want to compare.