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

Aldo Cortesi aldo at nullcube.com
Mon Jun 2 09:19:47 CEST 2003

Thus spake dsavitsk (dsavitsk at ecpsoftware.com):

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

Pure, blind luck - you are simply seeing an artifact of the
current Python implementation of dictionaries. You'll find
that this behaviour disappears for larger dictionary sizes.
It is also not guaranteed to exist in other versions of
CPython or in alternative Python implementations. 

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

Surely this doesn't warrant a PEP? You can easily define a
little helper function, if you really find that you use list
comprehensions on dictionaries often enough to make typing
the two lines above cumbersome: 

def sortAndReturn(lst):
    return lst

print [_months[i] for i in sortAndReturn(_months.keys())]

Alternatively, you can use any of the various ordered
dictionary implementations that are out there. One commonly
cited one can be found here:




Aldo Cortesi
aldo at nullcube.com

More information about the Python-list mailing list