Skip to content

Python Collections OrderedDict: Adding Order to Dictionaries

Python Collections OrderedDict - Adding Order to Dictionaries Cover Image

Python OrderedDicts are dictionary subclasses that maintain the order of the items added to them. Since Python 3.6, dictionaries in Python have maintained order. So this begs the question, why do we still need the OrderedDict class from the Python collections module? By the end of this tutorial, you’ll have gained a strong understanding of when using an OrderedDict is a better choice than using an ordered dictionary.

In this tutorial, you’ll learn about the OrderedDict class of the Python collections module. In particular, by the end of this tutorial, you’ll have learned the following:

  • How to create and use OrderedDict objects in your Python programs
  • Understand the differences between normal dictionaries and OrderedDicts
  • How to use the different methods specific to Python’s OrderedDicts

Understanding the Python collections OrderedDict

The OrderedDict class is part of the collections module in Python. It’s also a subclass of the normal Python dictionary, which means it has access to a lot of the functionality that normal Python dictionaries have. For example, OrderedDicts consist of items or rather key-value pairs.

What makes OrderedDicts unique is that they maintain the original order in which items were added. Similarly, the OrderedDict class provides two additional methods:

  1. .popitem(), which removes an item, either from the front or back of the OrderedDict
  2. .move_to_end(), which moves an item to either end of the OrderedDict

Since the collections module is built into Python, you don’t need to install anything to be able to use them. That said, OrderedDicts were first implemented in Python version 3.1. If you’re running an older version, you’ll need to upgrade your version of Python.

In the following section, you’ll learn how to create your first OrderedDict in Python.

How to Create an OrderedDict in Python

Creating an OrderedDict is simple. In order to do this, we can import the class from the collections module and then instantiate an OrderedDict object. Let’s see what this looks like:

# Creating Your First OrderedDict
from collections import OrderedDict

ordered = OrderedDict()
print(ordered)

# Returns:
# OrderedDict()

We can see that in this case, our OrderedDict is empty. We can verify that it’s a subclass of the regular Python dictionary by using the issubclass() function. With this function, we can pass in the OrderedDict class and the dictionary class.

# Confirm Subclassing of OrderedDict
from collections import OrderedDict

print(issubclass(OrderedDict, dict))

# Returns:
# True

We can see from the code above that the OrderedDict is a subclass of the normal Python dictionary. Now that we’ve covered that, let’s take a look at adding some items to the OrderedDict. We can load a few initial items, delete an item and add it back in. This will allow us to see how the order is maintained.

# Adding and Deleting Items
from collections import OrderedDict
ordered = OrderedDict({1: 1, 2: 2, 3: 3, 4: 4})

# Print OrderedDict
print('Before deleting item: ', ordered)

# Delete an Item
del ordered[3]

# Print Ordered Dict
print('After deleting item: ', ordered)

# Add a New Item
ordered[3] = 3

# Print Ordered Dict
print('After inserting item: ', ordered)

# Returns:
# Before deleting item:  OrderedDict([(1, 1), (2, 2), (3, 3), (4, 4)])
# After deleting item:  OrderedDict([(1, 1), (2, 2), (4, 4)])
# After inserting item:  OrderedDict([(1, 1), (2, 2), (4, 4), (3, 3)])

Let’s break down what we’re doing in the code block above:

  1. We create a new OrderedDict and print it
  2. We then delete an item using the del keyword and then print the OrderedDict
  3. Finally, we add the item again and print the OrderedDict

From this, we can see that Python maintains the order of the items, even when we delete and add new items. While dictionaries maintain order following Python 3.5, this implementation is available in versions going back to version 3.1.

When to Use an OrderedDict from Python collections

At this point, you’ve learned how to create an OrderedDict in Python using the collections module. However, you’ve also learned that starting in Python version 3.5, all dictionaries maintain order. This begs the question, why use OrderedDict at all?

There are four main reasons why you would still want to use OrderedDicts over normal dictionaries.

Manipulate the order of items

OrderedDicts allow you to apply two methods, .move_to_end() and .popitem(), to manipulate the order of items in the dictionary. This is unlike regular dictionaries, which either don’t have this behavior or have a lesser version of it.

Adding intentionality to code

When you need the readers of your code to know that the order of your dictionary is important, using an OrderedDict is the best way to do this. Given the overlap of functionality between OrderedDicts and dictionaries, it’s the perfect signal to the reader of your code.

Checking for equality between dictionaries

While normal dictionaries are ordered, comparing for equality between two dictionaries doesn’t check their order. If equality is determined by the items and their order, you need to use OrderedDicts.

Keep your code backward compatible

If you’re working with older versions of Python that predate version 3.5, you need to use OrderedDicts to add order to dictionaries. Since the class has been available in Python since version 3.1, you can use this function for code that goes back many years.

Now that you have a strong sense of how to create OrderedDicts and why you’d want to use them, let’s explore their functionality a little bit further. We’ll take a look at how to use both the .move_to_end() method and the .popitem() method.

Moving Items to the Front or Back of an OrderedDict

The OrderedDict class in the Python collections module has a helpful method, .move_to_end(), which allows you to move an item to the front or back or a dictionary. Let’s take a look at the method to see what functionality it provides:

# Understanding the .move_to_end() Method
from collections import OrderedDict
OrderedDict.move_to_end(key, last=True)

We can see that the method offers two parameters. Let’s take a closer look at these parameters:

  1. key= represents the key that you want to move, and
  2. last= represents whether to move an item to the last item or the first item. By default, it moves it to the last position.

Let’s see how we can use the method to move one of our items to the last position and another to the front:

# Move an Item to the End of an OrderedDict
from collections import OrderedDict

ordered = OrderedDict({1: 1, 2: 2, 3: 3, 4: 4})

ordered.move_to_end(1)
ordered.move_to_end(4, last=False)

print(ordered)

# Returns:
# OrderedDict([(4, 4), (2, 2), (3, 3), (1, 1)])

We can see that we used the method twice. The first method call moved the item with key 1 to the last position. The second method call moved to the item with key 4 to the front of the dictionary.

How to Pop or Remove Items from an OrderedDict

In this section, you’ll learn how to use the .popitem() method to pop either the first or last item from a Python OrderedDict. The default .pop() method is used to remove and return a particular item. However, the .popitem() method can be used to remove and return either the first or last item of an OrderedDict.

Let’s take a look at how the .popitem() method works:

# Understanding the .popitem() Method
from collections import OrderedDict
OrderedDict.popitem(last=True)

We can see that the function accepts only a single, optional argument. By default, the last= argument is set to True, meaning that the method pops the last item. If we change this parameter to False, the method removes the first item.

Let’s see how you can use the .popitem() method to remove an item from an OrderedDict:

# Pop the Last Item from an OrderedDict
from collections import OrderedDict

ordered = OrderedDict({1: 1, 2: 2, 3: 3, 4: 4})
removed = ordered.popitem()

print('ordered: ', ordered)
print('removed: ', removed)

# Returns:
# ordered:  OrderedDict([(1, 1), (2, 2), (3, 3)])
# removed:  (4, 4)

We can see that by default, the method removes the last item from the OrderedDict. In order to pop the first item from the OrderedDict, we can pass in last=False into the method:

# Pop the First Item from an OrderedDict
from collections import OrderedDict

ordered = OrderedDict({1: 1, 2: 2, 3: 3, 4: 4})
removed = ordered.popitem(last=False)

print('ordered: ', ordered)
print('removed: ', removed)

# Returns:
# ordered:  OrderedDict([(2, 2), (3, 3), (4, 4)])
# removed:  (1, 1)

We can see that by modifying the argument, the method removes and returns the first item from the OrderedDict.

Conclusion

In this tutorial, you learned how to use the OrderedDict class from the Python collections module. The OrderedDict provides you with the functionality to order a dictionary and maintain that order. That said, Python has offered ordered functionality to dictionaries since Python version 3.5. Despite this, the class still serves a lot of purposes and makes your code much more intentional (as well as backward compatible).

You first learned how to create an OrderedDict using the collections dictionary. From there, you learned how to check how the dictionary maintains order. You also learned how to use OrderedDict’s two special methods to customize behavior. You learned how to move items to the front or back using the .move_to_end() method. Then, you learned how to remove either the first or last item using the .popitem() method.

Additional Resources

To learn about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

Your email address will not be published. Required fields are marked *