Re: dictionaries...

Consultant (amrit@xvt.com)
Mon, 18 Jul 1994 10:50:51 -0600 (MDT)

> Given this dictionary:
>
> months = { 'jan':1,
> ........
> 'dec':12
> }
>
>
> What is the easy way to enumerate the keys in the order they are
> declared above?
>
In this case, you can take advantage of the fact that if you sort the
values, then the keys will be in the order you want. Realizing this,
I wrote a Python program that gets the dictionarie's items(), sorts
them from the value field (sort() can take a second argument which
can be a compare function, great when the default sort is not what
you want), then iterates over the keys.

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 :-)