How to Easily Use OrderedDict in Python
OrderedDict vs dict in Python: The Right Tool for the Job
Sometimes you need a Python dictionary that remembers the order of its items. In the past, you had only one tool for solving this specific problem: Python’s OrderedDict
. It’s a dictionary subclass specially designed to remember the order of items, which is defined by the insertion order of keys.
This changed in Python 3.6. The built-in dict
class now keeps its items ordered as well. Because of that, many in the Python community now wonder if OrderedDict
is still useful. A closer look at OrderedDict
will uncover that this class still provides valuable features.
In this tutorial, you’ll learn how to:
- Create and use
OrderedDict
objects in your code - Identify the differences between
OrderedDict
anddict
- Understand the pros and cons of using
OrderedDict
vsdict
With this knowledge, you’ll able to choose the dictionary class that best fits your needs when you want to preserve the order of items.
Choosing Between OrderedDict and 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 its 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 keys were inserted. That was the origin of OrderedDict
.
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.
Getting Started With Python’s OrderedDict
Let’s start by exploring how to work with OrderedDict
in Python.
Creating OrderedDict Objects
To create an OrderedDict
object, you import the OrderedDict
class from the collections
module and instantiate it with or without initial items. Here’s an example that shows both cases:
In the code above, ordered_dict_empty
is an empty OrderedDict
, while ordered_dict
is an OrderedDict
with three initial items.
Managing Items in an OrderedDict
Once you have an OrderedDict
, you can add, update, and remove items using familiar dictionary methods.
To add an item, you use the indexing operator or the update()
method. Here are examples of both approaches:
In the code above, the first line adds an item with key 'd'
and value 4
to the ordered_dict
. The second line uses the update()
method to add two items at once.
To update an item, you also use the indexing operator. Here’s an example:
In this case, the item with key 'd'
is updated with the new value 8
.
To remove an item, you can use either the del
statement or the pop()
method. Here are examples of both approaches:
In the code above, the first line removes the item with key 'd'
from the ordered_dict
. The second line uses the pop()
method to remove and return the item with key 'e'
.
Iterating Over an OrderedDict
One of the advantages of OrderedDict
is that it preserves the order of its items. You can iterate over an OrderedDict
just like you would with a regular dictionary, and the items will be returned in the order they were inserted.
Here’s an example:
In the code above, the items()
method returns a list of key-value pairs from the ordered_dict
in the order they were inserted. The for
loop then prints each key-value pair.
Iterating in Reversed Order With reversed()
OrderedDict
also provides a way to iterate over its items in reversed order using the reversed()
function. Here’s an example:
In the code above, the reversed()
function returns an iterator that yields the keys from the ordered_dict
in reverse order. The for
loop then prints each key-value pair in reversed order.
Exploring Unique Features of Python’s OrderedDict
Now that you know the basics of working with OrderedDict
, let’s explore some of its unique features that differentiate it from a regular dict
.
Reordering Items With .move_to_end()
OrderedDict
provides a method called move_to_end()
that allows you to change the order of items by moving them to either the beginning or the end of the dictionary. Here’s an example:
In the code above, the item with key 'c'
is moved to the end of the ordered_dict
.
You can also specify the last
parameter as False
to move the item to the beginning of the dictionary. Here’s an example:
In this case, the item with key 'c'
is moved to the beginning of the ordered_dict
.
Removing Items With .popitem()
In addition to the pop()
method, OrderedDict
provides a method called popitem()
that removes and returns the last inserted item if no arguments are passed. If an argument is provided, it behaves just like the regular pop()
method.
Here’s an example that demonstrates the use of popitem()
:
In this code, the popitem()
method removes and returns the last inserted item as a key-value pair.
Testing for Equality Between Dictionaries
When comparing dictionaries for equality, the order of the items matters for OrderedDict
, but not for a regular dict
. This means that two OrderedDict
objects with the same items in a different order are considered different, while two regular dict
objects with the same items in a different order are considered equal.
Here’s an example that illustrates this difference:
In this code, dict1
and dict2
are considered equal because the order of the items doesn’t matter for a regular dict
. However, ordered_dict1
and ordered_dict2
are not considered equal because the order of the items matters for OrderedDict
.
Appending New Attributes to a Dictionary Instance
One interesting feature of OrderedDict
is the ability to append new attributes to a dictionary instance. This allows you to attach additional information to a specific OrderedDict
object.
Here’s an example:
In this code, the attribute extra_info
is appended to the ordered_dict
instance. This can be useful if you need to attach metadata or other data to a specific OrderedDict
object.
Merging and Updating Dictionaries With Operators
Both OrderedDict
and dict
provide methods for merging and updating dictionaries. However, OrderedDict
also allows you to use the +
operator for merging dictionaries and the -
operator for removing items based on keys.
Here’s an example that demonstrates these operations:
In this code, ordered_dict1.update(ordered_dict2)
merges the two OrderedDict
objects using the update()
method. The ordered_dict1 + ordered_dict2
statement also merges the dictionaries, but it uses the +
operator instead. The merged_ordered_dict - ordered_dict2
statement removes the items from ordered_dict2
in the merged_ordered_dict
using the -
operator.
Considering Performance
When deciding between OrderedDict
and dict
, it’s important to consider their performance characteristics. OrderedDict
has an additional overhead to keep track of the order of items, which can impact the performance for large dictionaries. Regular dict
, on the other hand, doesn’t have this overhead and can be more performant in certain scenarios.
If you need to preserve the order of items and performance is not a concern, then OrderedDict
is a suitable choice. However, if you’re working with large dictionaries and performance is critical, then a regular dict
might be a better option.
Selecting the Right Dictionary for the Job
Both OrderedDict
and dict
have their use cases. Consider the following factors when selecting the right dictionary for your needs:
- Do you need to preserve the order of items?
- Are you working with large dictionaries where performance is critical?
- Do you need to append new attributes or metadata to a dictionary instance?
By answering these questions, you can determine whether OrderedDict
or a regular dict
is the right tool for the job.
Building a Dictionary-Based Queue
To demonstrate the usefulness of OrderedDict
, let’s implement a dictionary-based queue using OrderedDict
. This queue will keep track of the order in which items are inserted and allow for efficient insertions and deletions.
Here’s an example implementation:
In this code, the Queue
class uses an OrderedDict
object to implement a queue data structure. The enqueue()
method adds an item to the end of the queue, the dequeue()
method removes and returns the item at the beginning of the queue, the is_empty()
method checks if the queue is empty, and the size()
method returns the size of the queue.
Conclusion
In this tutorial, you’ve learned about the differences between OrderedDict
and dict
in Python. Although dict
now preserves the order of items, OrderedDict
still provides valuable features that make it a useful tool in certain scenarios. By understanding the strengths and weaknesses of both classes, you can choose the dictionary class that best suits your needs when you want to preserve the order of items.