EDIT (2019-02-03)
Note that the following answer only works on older versions of Python. More recently, OrderedDict
has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.
I just wrote a subclass of OrderedDict
in a project of mine for a similar purpose. Here's the gist.
Insertion operations are also constant time O(1)
(they don't require you to rebuild the data structure), unlike most of these solutions.
>>> d1 = ListDict([('a', '1'), ('b', '2')])
>>> d1.insert_before('a', ('c', 3))
>>> d1
ListDict([('c', 3), ('a', '1'), ('b', '2')])