Keys order in dictionaries

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jun 27 04:53:10 EDT 2003


Brainwashed <vald at valis.amber.eu.org> wrote in
news:mailman.1056670245.3458.python-list at python.org: 

> Is there any order in dictionaries that will never change ? I've
> noticed that assigning always the same elements to the dict puts them
> always in the same order. Like regexp which takes 3 values, 'year',
> 'month', 'day' - I always get this order:
> 
>   'year': .., 'day':.., 'month':..
> 
> No idea why this order tho.. :) Is there any philosophy in this ?
> 

Just because you never saw the order change doesn't mean it won't change. 
The code below shows just how easy it is to force the order to change:

>>> d = { 'year': 1, 'month': 2, 'day': 3 }
>>> d
{'month': 2, 'day': 3, 'year': 1}
>>> for i in range(30):	d[i] = i

>>> for i in range(30):	del d[i]

>>> d
{'month': 2, 'year': 1, 'day': 3}
>>> dict(d)
{'year': 1, 'day': 3, 'month': 2}
>>> 

(BTW, that last one surprised me, I had expected dict(d) simply to restore 
the original order instead of producing a third ordering).

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list