2

Possible Duplicate:
Python dictionary, keep keys/values in same order as declared

I'm going through some exercises on code academy when I noticed the dictionaries I was creating inside my python interpreter were coming back with unexpected results.

I'm using python2.7 and when I enter:

>>> dict_a = {'x':9, 'y':10, 'z':20}

And I call it:

>>> dict_a
{'y':10, 'x':9, 'z':20}

So I put in:

>>> dict_b = {'a':1, 'b':2, 'c':3}
>>> dict_b
{'a':1, 'c':3, 'b':2}

I'm thinking I've missed something basic here but, after doing some searching I don't know what? If someone could help explain why this is happening, it would be very much appreciated.

Community
  • 1
  • 1
tijko
  • 7,599
  • 11
  • 44
  • 64

2 Answers2

10

Dictionaries are unsorted. The order they display in is due to internal logic, and won't correspond to the order you define them in. However, since you don't access a dictionary by order but by key, this rarely matters.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 5
    In the rare case it does matter, there is [``collections.OrderedDict``](http://docs.python.org/py3k/library/collections.html#collections.OrderedDict). – Gareth Latty Oct 11 '12 at 10:53
  • @Lattyware I'm going to see if I can `import collections` into the sites interpreter because right now looping through the `keys` is not returning the _correct_ results. The site has been buggy though. Thanks everyone else for the quick replies :) – tijko Oct 11 '12 at 10:58
  • @Daniel Roseman I've probably have been over this before but, it didn't matter much because as you said I would normally just call on the dictionary by key. It seems that order is making the difference here but, as I said in my comment above the site has had its problems, thanks :) – tijko Oct 11 '12 at 11:01
  • 1
    Not just unsorted, un-*ordered*. A list is ordered but not sorted. A dictionary is neither. –  Oct 11 '12 at 11:25
  • @delnan **ordered** meaning how it was passed in? – tijko Oct 11 '12 at 11:31
  • 2
    @tijko Basically, with an ordered collection you can rely on some ordering of the elements. With lists, the order is explicitly controlled by how you add and remove elements. With OrderedDict, the order is (discounting a rarely-used method) controlled by when a key was first seen. Sorted is a stronger statement meaning that the collection is not only ordered, but ordered by sorting the elements. We have few examples of sorted collections in Python, but the `bisect` module maintains a sorted list. In other languages, sets and dicts based on trees are common, and those are sorted. –  Oct 11 '12 at 11:52
0

This is a normal behaviour, the dictionary does not have an inherent internal order, so it is perfectly fine.

Ricardo Rodriguez
  • 1,010
  • 11
  • 22