This is certainly doable, as Yevgeniy Kosmak's answer shows. However, keep in mind that in Python >=3.7 (or even >=3.6 as long as you're using the default CPython implementation), all dictionaries now maintain insertion order anyway. So in the event that you don't need compatibility with older versions, and the only thing you need is keys that maintain order, you may very well not need OrderedDict
at all. defaultdict
will maintain its order just as well.
There are still some differences between OrderedDict
and dict
/defaultdict
, however, which may or may not affect your use case. These include:
- Equality checks between two
OrderedDict
s check not only keys/values, but order as well. (This is not true of two defaultdict
s, or an OrderedDict
checked against a defaultdict
.)
- An
OrderedDict
's move_to_end()
method can efficiently move a key/value pair to the front or end.
- An
OrderedDict
's popitem()
method can optionally pop and return the first key/value instead of the last. (dict
's popitem()
returns the last-inserted key/value—or, prior to 3.7, an arbitrary pair.)
- Prior to 3.8,
dict
/defaultdict
didn't directly support reverse iteration, such as with reversed()
. However, in 3.6 or 3.7 you can still achieve this with an intermediary list or tuple.
Note: Even if dict
now replicated all of OrderedDict
's functionality, the latter would still probably not be removed from Python. Existing older programs already use OrderedDict, and Python usually tries not to break existing code with new minor version releases (e.g. 3.6 to 3.7) unless there's a compelling reason, like adding new keywords to the syntax. See here for more info on the Python versioning system, and here for details on backwards compatibility specifically.