Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is a dictionary sorted?

Tags:

python

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?

like image 218
mohsen Avatar asked Aug 15 '26 08:08

mohsen


2 Answers

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 (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')])
like image 126
Chris B. Avatar answered Aug 16 '26 22:08

Chris B.


Dictionaries are unordered data structures, so you should have no expectations

like image 34
TJD Avatar answered Aug 16 '26 23:08

TJD