Is numeric keys of Python's dictionary automatically sorted?

Duncan Booth duncan.booth at invalid.invalid
Thu Mar 8 03:35:31 EST 2007


Carsten Haese <carsten at uniqsys.com> wrote:

> Here is a simple counterexample that breaks the ordering, at least for
> the version I'm running:
> 
>>>> d = {}
>>>> for i in range(0,6): d[10**i] = []
> ... 
>>>> d
> {100000: [], 1: [], 100: [], 1000: [], 10: [], 10000: []}

Here's another counterexample which shows that even dictionaries with 
the same consecutively numbered small integer keys can vary the order in 
which the keys are returned:

>>> d1 = dict.fromkeys([1,2])
>>> d2 = dict.fromkeys([9,1,2])
>>> del d2[9]
>>> d1
{1: None, 2: None}
>>> d2
{2: None, 1: None}

In current C-Python implementations, the hash code for an integer is 
simply the integer itself. That means there is a strong tendency for 
consecutive integers to be stored in consecutive slots in the 
dictionary. However as soon as you get gaps, or add the keys out of 
order, there is a opportunity for higher valued keys to displace lower 
valued keys into a different slot.

If you want the keys sorted then sort them.



More information about the Python-list mailing list