Is numeric keys of Python's dictionary automatically sorted?

Duncan Booth duncan.booth at invalid.invalid
Thu Mar 8 11:40:12 CET 2007


Steven D'Aprano <steve at REMOVEME.cybersource.com.au> wrote:

> If they are better-than
> average, they might try this:
> 
>>>> D = {1: None, 4: None, 3:None} # keys out of order
>>>> D
> {1: None, 3: None, 4: None}
> 
> Still ordered, right? It's actually quite hard to get a dict with purely
> integer keys out of order.

It isn't hard at all.

The next step would be to try something with a few more than 3 keys and 
decide that you can't be bothered with all that typing and inventing 
values.

dict.fromkeys([randint(0,99) for i in range(10)])

gives you keys out of order about 99.92% of the time.




More information about the Python-list mailing list