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

Oren Tirosh oren-py-l at hishome.net
Mon Jun 2 03:35:48 EDT 2003


On Mon, Jun 02, 2003 at 05:45:32AM +0000, dsavitsk wrote:
> (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.

>>> [hash(i) for i in range(1,12)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Dictionaries use the hash function of objects and the hash function of 
an integer is the number itself. This is not guaranteed to generate the
keys in numeric order, but it usually does. One thing it does guarantee
is that a dictionary indexed by any contigous range of numbers will 
never have collisions in its internal hash table. You don't see such
collisions but they affect performance.

Don't write code that relies on this ordering, though.

    Oren





More information about the Python-list mailing list