'''Demonstrates how you can control list.sort by giving it a function
to use when comparing two elements of the list.
Notice that we sort the list of strings by putting the the ones that are
"smallest" in a sense at the front, but we later sort a list of dicts by
putting the ones that are "biggest" in a sense at the front. What determines
this orientation (ascending or descending order) is the return value from the
function we pass to sort. We simply need that function to return -1 if the
first argument should appear before the second argument in the final sorted
list, +1 if it should appear after, and 0 if their relative order doesn't
matter.'''
def biggest_max(d1, d2):
'''d1 and d2 are dicts whose values are ints. Return -1 if the maximum
value in d1 is bigger than the average value in d2, 1 if it is smaller,
and 0 if they are equal.'''
d1_average = max(d1.values())
d2_average = max(d2.values())
if d1_average > d2_average:
return -1
elif d1_average < d2_average:
return 1
else:
return 0
def shorter(s1, s2):
'''Return -1 if string s1 is shorter than string s2, +1 if it is longer,
and 0 if they have equal length.'''
if len(s1) < len(s2):
return -1
elif len(s1) > len(s2):
return 1
else:
return 0
if __name__ == "__main__":
L = ["Once", "upon", "a", "time", "there", "was", "a", "curious", "girl"]
# Sort the list using Python's default behaviour. It will sort
# alphabetically.
L.sort()
print L
# Now sort it so that we control how pairs of list items are compared.
# Tell sort to compare using function shorter. The shorter strings
# will be at the front of the updated list.
L.sort(shorter)
print L
# Now try sorting a list of dicts.
L2 = [{"Jo": 2, "Nate": 99, "Mari": 45}, {"Zara": 2},
{"Reuben": 54,"Zoya": 11, "Jiaqi": 9}, {"Myrka": 23, "Harbinder": 18}]
# Sort the list of dicts using Python's default behaviour. Goodness knows
# how it will decide to order the dicts.
L2.sort()
print L2
# Now tell Python to sort using the biggest_max function. Dictionaries
# whose maximum key is largest will be at the front of the udpated list.
L2.sort(biggest_max)
print L2