So when you're printing key-value pairs in a dictionary, do they get printed in any particular order? (Python)
When printing key-value pairs in a dictionary, do they get printed in any particular order? (Python)
3 Answers
There will be an order (there has to be) but the order is not guaranteed to be the same every time. If you need to order your results then use an OrderedDict or sort the data separately in a list.

- 5,837
- 2
- 26
- 46
The order will depend on the exact order you added and deleted items to the dictionary. It also depends on the version of Python and in more recent versions of Python it may even be different on different runs of your application.
For example, Python 2.7:
>>> dict.fromkeys("abi")
{'a': None, 'i': None, 'b': None}
>>> dict.fromkeys("iba")
{'i': None, 'a': None, 'b': None}
But Python 3.3:
>>> dict.fromkeys("abi")
{'a': None, 'b': None, 'i': None}
and again in Python 3.3 but after restarting the interpreter:
>>> dict.fromkeys("abi")
{'b': None, 'a': None, 'i': None}
You should avoid falling into the trap of thinking that there is an order. In older versions of Python you could actually work out what order to expect, but basing any of your code on that is simply asking for trouble. The commonest pitfall here is probably when writing doctests: it is very easy to write a doctest which asserts an order for a dictionary and then your code fails when the order changes.

- 92,073
- 11
- 122
- 156
Dictionaries in general are unordered, but this is only under the understanding that it is not ordered in the way you set it out to be. Python shuffles them about so that it can use a hash table to search for keys quicker than it would through a list or tuple.
This means that the dictionary does have an order, but it is not immediately obvious and does not need to be understood by the user.

- 4,056
- 4
- 21
- 36