Choosing Between OrderedDict and dict
dict. For years, Python dictionaries were unordered data structures. Python developers were used to this fact, and they relied on lists or other sequences when they needed to keep their data in order. With time, developers found a need for a new type of dictionary, one that would keep the items ordered.
Back in 2008, PEP 372 introduced the idea of adding a new dictionary class to
collections. Its main goal was to remember the order of items as defined by the order in which the keys were inserted. That was the origin of
00:36 Core Python developers wanted to fill in the gap and provide a dictionary that could preserve the order of inserted keys. That, in turn, allowed for a more straightforward implementation of specific algorithms that rely on this property.
OrderedDict was added to the standard library in Python 3.1. Its API is essentially the same as
OrderedDict iterates over keys and values in the same order that the keys were inserted. If a new entry overwrites an existing entry, then the order of items is left unchanged.
Initially, this feature was considered an implementation detail, and the documentation advised against relying on it. In Python 3.7, the items-ordered feature of
dict objects was declared an official part of the Python language specification. So, from that point on, developers could rely on
dict if they needed a dictionary that keeps its items ordered. At this point, a question arises: Is
OrderedDict still needed after this new implementation?
The answer depends on your specific use case and also how explicit you want to be in your code. Some features of
OrderedDict still make it valuable and different from a regular
dict. First, intent signaling.
If you use
dict, then your code makes it clear that the order of items in the dictionary is important. You are clearly communicating that your code needs or relies on the order of items in the underlying dictionary. Control over the order of items.
There’s at least one more reason to continue using
OrderedDict in your code: backwards compatibility. Relying on regular dictionaries to preserve the order of items will break your code in environments that run versions of Python older than 3.6.
It’s difficult to say if
dict will ever fully replace
OrderedDict. At the moment,
OrderedDict still offers interesting and valuable features that you might want to consider when selecting a tool for a given job.
Become a Member to join the conversation.