OrderedDict Isn’t Dead Yet — Here’s Why

Do you still need OrderedDict in your code now that dict preserves insertion order?

Sometimes, we need dictionary items (key-value pairs) to retain the order in which they were added. For a long time, Python’s built-in dict type didn’t preserve insertion order, so we had to rely on OrderedDict from the collections module.

However, since Python 3.7, the standard dict maintains insertion order by default. And starting with Python 3.8, it can even be used with the reversed() function—just like OrderedDict.

This naturally raises the question: Does OrderedDict still have a reason to exist? If yes, when?

While the importance of OrderedDict has indeed diminished, it’s not completely obsolete. Beyond maintaining compatibility with code written for Python 3.6 or earlier, there are still some use cases where OrderedDict offers features that can simplify code or improve readability:

  • Unlike dict, OrderedDict has a move_to_end(key, last=True) method, which moves the specified key either to the end or to the beginning of the dictionary depending on the last argument.
  • Compared to the built-in dict.popitem() method—which removes the last inserted item (LIFO), OrderedDict.popitem(last=False) lets you remove the first inserted item instead (FIFO).

    Example: A Doctor’s Waiting Room

    Let’s take an example that models a medical waiting room using an OrderedDict. Patients arrive with different complaints and bring lab or screening results with them. The doctor sees patients in the order they arrive, except for those with a fever, who get priority. Patients are then called in one by one, and the doctor makes a diagnosis based on whether their lab result is positive or negative.

    This example uses both the move_to_end() and popitem()methods.

    The OrderedDict type, as well as other language elements used in this example, is explained in detail in the e-book Python Knowledge Building Step by Step.

    Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?