dictionary issue (and maybe PEP ... depending on the answer)

dsavitsk dsavitsk at ecpsoftware.com
Mon Jun 2 07:45:32 CEST 2003


(Python 2.2.1 on FreeBSD 4.7 being used via mod_python 3)

I have a dictionary at the top of a module that looks like this

_months = {1: 'January',
	   2: 'February',
	   3: 'March',
	   4: 'April',
	   5: 'May',
	   6: 'June',
	   7: 'July',
	   8: 'August',
	   9: 'September',
	   10: 'October',
	   11: 'November',
	   12: 'December'}

never mind, for now, that there are proably better ways to do what the 
dict obviously does.  anyhow, I get a list of the months by doing this

 >>> [_months[i] for i in _months.keys()]

The issue is, this consistently returns the months in order. I don't see 
any obvious reason that it does, but I can't get it to fail. So,I am 
wondering if there is a reason, or is it serendipity.

Assuming that there is not a good reason, the PEP idea is adding a 
sorted_keys() method to dictionaries which would just return the keys in 
the same order they would be in by doing this.

 >>> l = d.keys()
 >>> l.sort()

The advantage is that using dictionary keys in list comprehensions would 
be easier, but other than that it is not too big a deal.

Thanks,

Doug





More information about the Python-list mailing list