corvid corvid - 5 months ago 12
Python Question

OrderedDict not staying in order

The idea of this loop was to iterate through a list. If a certain property of an object was not a key of the OrderedDict, it would add it. It is a dictionary of lists of objects

for object in someList:
if object.DATE not in myOrderedDict:

while it does seem to make the OrderedDict mostly correctly, it ends up out of order when it's printed. Instead of having something like
(01/13) (02/13) (03/13)
it goes more like
(02/13) (03/13) (01/13)

Why does this happen and how can it be fixed?


It would appear that you expect the items in an OrderedDict to be ordered by key, which is not the case. An OrderedDict is ordered by the order items are added to it. From the PEP 372 FAQ:

Does OrderedDict support alternate sort orders such as alphabetical?

No. Those wanting different sort orders really need to be using another technique. The OrderedDict is all about recording insertion order. If any other order is of interest, then another structure (like an in-memory dbm) is likely a better fit.