-1

I need my code to always iterate over the dict items (through dict.keys()) in the order they were instantiated. However I noticed that when you instantiate a dict in Python, it will NOT be ordered:

>>> dict = {'a':'a', 'b':'b', 'c':'c'}
>>> dict
{'a': 'a', 'c': 'c', 'b': 'b'}
>>> for x in dict.keys():
...     print x
a
c
b

How can I guarantee that whenever I iterate through this dict, it will always be in the same order that I created it? And why does Python seem to "scramble" the values whenever I instantiate a new dict?

Note that the order that I talk about here is NOT necessarily alphabetical, numerical or of any other sortable kind.

devnull
  • 443
  • 6
  • 13
  • As long as you don't alter the keys in the dictionary (insert or delete keys), the order remains stable. – Martijn Pieters Aug 12 '14 at 18:45
  • If you need a fixed order, use an `collections.OrderedDict` object instead. – Martijn Pieters Aug 12 '14 at 18:45
  • 1
    See Brandon Rhodes' talk [The Mighty Dictionary](https://www.youtube.com/watch?v=C4Kc8xzcA68) for all the gory details on dictionary construction and resizing (if you're interested in the answer to the exact question from your title). – Lukas Graf Aug 12 '14 at 18:49

1 Answers1

2

Try using a collections.OrderedDict. Documentation.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Roger Fan
  • 4,945
  • 31
  • 38