Is numeric keys of Python's dictionary automatically sorted?

Nick Vatamaniuc vatamane at
Thu Mar 8 08:34:20 CET 2007

On Mar 7, 3:49 pm, "John" <rds1... at> wrote:
> Then is there anyway to sort the numeric keys and avoid future implemetation
> confusion?
> "Ant" <ant... at> wrote in message
> news:1173300100.810023.223130 at
> > On Mar 7, 8:18 pm, "John" <rds1... at> wrote:
> > ...
> >> However, I am not sure whether it is always like this. Can anybody
> >> confirm
> >> my finding?
> >>From the standard library docs:
> > "Keys and values are listed in an arbitrary order which is non-random,
> > varies across Python implementations, and depends on the dictionary's
> > history of insertions and deletions."
> > i.e. the behaviour you have discovered is an implementation detail,
> > and could change in future versions.

I would consider that a bad choice. In the dictionary the keys are a
set i.e. you might as well get a set() when you do d.keys() but the
set() came later so you just get a list. The problem with a list is
that somehow people want to make sense of it's order, just like in
this case. So if instead of asking, he could have just written the
application based on the fact that the keys will always be sorted in
some way. But then one day his application maybe run a different
platform and all of the sudden the keys are not sorted as before and
then disaster strikes.

I hope that dictionary.keys() would return a set to emphasize that
keys are unordered.

You suggested to just set a sort order and keep it consistent, but the
problem is that then you _have to_ maintain the sort order in addition
to the regular dictionary implementation (now it might just be a
byproduct), that is extra work that will have to be done on every
single insertion or deletion just for that rare use case where someone
will want the keys to be sorted.

More information about the Python-list mailing list