Storing Python dictionary entries in the order they are pushed

Implementations of order-preserving dictionaries certainly do exist.

There is this one in Django, confusingly called SortedDict, that will work in Python >= 2.3 iirc.


Try python 2.7 and above, probably 3.1, there is OrderedDict

http://www.python.org/

http://python.org/download/releases/2.7/

>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1), ('second', 2),
...                  ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]

PEP 372: Adding an ordered dictionary to collections


Use a list to hold the key order


Dictionaries in Python are implemented as hash tables, which is why the order appears random. You could implement your own variation of a dict that sorts, but you'd lose out on the convenient syntax. Instead, keep track of the order of the keys, too.

Initialization:

keys = []
myDict = {}

While reading:

myDict[key] = value
keys.append(key)

While writing:

for key in keys:
  print key, myDict[key]