how is a dictionary sorted?
Question: Ladies and Gents,

I have a question about dictionaries in python. While playing around I noticed
something that _to me_ seems strange.

I define a dict like this

stuff={'age':26,'name':'Freddie Mercury', 'ciy':'Vladivostok'}

I then add the word 'first' to stuff like this:

> stuff[1]='first'

When I print it out, it's fine

> stuff
>
> {1: 'first', 'age': 26, 'name': 'Freddie Mercury', 'city': 'Vladivostok'}

Then I add the word second:

> stuff[2]='second'

and that's fine, but when I display the content I get:

> stuff
>
> {1: 'first', 'age': 26, 2: 'second', 'name': 'Freddie Mercury', 'city':
> 'Vladivostok'}

** notice that 2 is now the third element, and not the second (in order) or
the first (if elements are added to the beginning) element

And when I add in the third element 'wtf', now all of a sudden everything is
back in order and I'm quite confused as to what's going on.

> stuff[3]='wtf'
>
> stuff
>
> {1: 'first', 2: 'second', 3: 'wtf', 'name': 'Freddie Mercury', 'age': 26,
> 'city': 'Vladivostok'}

Could someone please explain to me what's going on here?


Answer: The order you get from a dictionary is undefined. You should not rely on it.
In this case, it happens to depend on the hash values of the underlying keys,
but you shouldn't assume that's always the case.

If order matters to you, use should use an
[OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict)
(since Python 2.7):

    
    
    >>> from collections import OrderedDict
    >>> stuff=OrderedDict({'age':26,'name':'Freddie Mercury', 'city':'Vladivostok'})
    >>> stuff[1]='first'
    >>> print stuff
    OrderedDict([('city', 'Vladivostok'), ('age', 26), ('name', 'Freddie Mercury'), (1, 'first')])
    >>> stuff[2]='second'
    >>> print stuff
    OrderedDict([('city', 'Vladivostok'), ('age', 26), ('name', 'Freddie Mercury'), (1, 'first'), (2, 'second')])
    >>> stuff[3]='wtf'
    >>> print stuff
    OrderedDict([('city', 'Vladivostok'), ('age', 26), ('name', 'Freddie Mercury'), (1, 'first'), (2, 'second'), (3, 'wtf')])
    

