Python OrderedDict not keeping element order [duplicate]

Your problem is that you are constructing a dict to give the initial data to the OrderedDict – this dict doesn’t store any order, so the order is lost before it gets to the OrderedDict.

The solution is to build from an ordered data type – the easiest being a list of tuples:

>>> from collections import OrderedDict
>>> od = OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])
>>> od
OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])

It’s worth noting that this is why OrderedDict uses the syntax it does for it’s string representation – string representations should try to be valid Python code to reproduce the object where possible, and that’s why the output uses a list of tuples instead of a dict.

Edit: As of Python 3.6, kwargs is ordered, so you can use keyword arguments instead, provided you are on an up-to-date Python version.

As of 3.7, this is also true for dicts (it was for CPython in 3.6, but the language spec didn’t specify it, so using OrderedDict was still required for compatibility). This means if you can assume a 3.7+ environment, you can often drop OrderedDict altogether, or construct one from a regular dict if you need a specific feature (e.g: order to matter for equality).

Leave a Comment