I included a special routine I wrote which will sort any datatype
(I use it for lists, tuples, & other sequencables), that is also
more conveinent to call than the sort() method, due to its functional
form.
# cal.py
months = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4,
'may': 5,
'jun': 6,
'jul': 7,
'aug': 8,
'sep': 9,
'oct': 10,
'nov': 11,
'dec': 12
}
# We can get the natural ordering of month names from the dictionary,
# by sorting the values of the dictionary. That's what we do here.
def sort(seq, func = lambda x, y: cmp(x, y)):
seq = map(None, seq) # convert sequence to list
seq.sort(func)
return seq
def applyToMonths(proc):
items = sort(months.items(), lambda x,y: cmp(x[1], y[1])) # compare values
for item in map(lambda x: x[0], items): # apply over keys
proc(item)
from sys import stdout
applyToMonths(lambda x: stdout.write(x + '\n'))
- Or, if you prefer the longish way:
items = months.items()
items.sort(lambda x,y: cmp(x[1], y[1]))
for item in map(lambda x: x[0], items): print item
This is the essence of the idea, but I do tend to get carried away :-)