Re: dictionaries...

Rickard Westman (ricwe@ida.liu.se)
Mon, 18 Jul 1994 12:38:00 GMT

"Ron Forrester" <rjf@aurora.pcg.com> writes:

>Given this dictionary:

>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
> }

First, a small suggestion: Name the dictionary after the values, not after the
keys. Otherwise it gets confusing. For instance,

surname['Ron'] = 'Forrester'

reads better than

first_names['Ron'] = 'Forrester'

>What is the easy way to enumerate the keys in the order they are
>declared above?

In general, it is impossible to enumerate a dictionary in declaration order,
since this information is not stored in the dictionary. In your example, the
declaration order is the same as the numerical order of the values, so one way
would be to invert the index and loop over the keys in the inverted index:

months_inv = {}
for key in months.keys():
months_inv[months[key]]=key
for i in range(1,13):
do_something_with(months_inv[i])

Do you create the dictionary yourself? In that case it might be better to
create a list of months (giving you the enumeration you want) and create the
dictionary from the list instead:

months = [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
'sep', 'oct', 'nov', 'dec' ]
month_num = {}
for month in months:
month_num[month]=len(month_num)+1

In any case you handle ordering yourself in some way, since dictionaries are
ineherently unordered animals.

--
Rickard Westman <ricwe@ida.liu.se>  |  "I think not."
Programming Environments Laboratory |
University of Linkvping, Sweden     |        - Descartes' last words?
------------------------------------+------------------------------------