Python’s collections
module provides a powerful and efficient implementation of ordered dictionaries using the OrderedDict
class. In this article, we will learn how to use OrderedDict
in Python with step-by-step code examples, supported functions, and when to use it and when not to use it.
What is an ordered dictionary?
An ordered dictionary is a dictionary that maintains the order of the keys as they are inserted. In a standard dictionary, the order of the keys is arbitrary, and may change from one Python run to the next. In an ordered dictionary, the order of the keys is fixed and will remain the same every time you iterate over the keys.
Creating an OrderedDict
instance
To create an OrderedDict
instance, we can simply import the OrderedDict
class from the collections
module and create a new instance like this:
from collections import OrderedDict
od = OrderedDict()
This creates an empty ordered dictionary od
.
We can also create an ordered dictionary from a list of key-value pairs. The order of the keys in the list will determine the order in which they are added to the dictionary.
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od)
Output:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
In this example, we create an ordered dictionary with three key-value pairs: ('a', 1), ('b', 2), and ('c', 3)
.
Supported functions
OrderedDict
has all the standard dictionary methods and attributes, as well as a few additional methods that take advantage of the ordered nature of the dictionary.
move_to_end()
The move_to_end()
method moves a key to either end of the ordered dictionary. By default, it moves the key to the end of the dictionary, but you can also specify 'last'
or 'first'
to move it to the end or beginning, respectively.
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
od.move_to_end('a')
print(od)
od.move_to_end('c', last=False)
print(od)
Output:
OrderedDict([('b', 2), ('c', 3), ('a', 1)])
OrderedDict([('c', 3), ('b', 2), ('a', 1)])
In this example, we move the key 'a'
to the end of the dictionary, and then move the key 'c'
to the beginning of the dictionary.
popitem()
The popitem()
method removes and returns the last key-value pair from the dictionary. If the dictionary is empty, it raises a KeyError
exception.
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
item = od.popitem()
print(item)
print(od)
Output:
('c', 3)
OrderedDict([('a', 1), ('b', 2)])
In this example, we remove the last key-value pair from the dictionary, which is ('c', 3)
.
keys()
, values()
, and items()
The keys()
, values()
, and items()
methods return the keys, values, and key-value pairs in the dictionary, respectively. These methods return views into the dictionary that are ordered by the order in which the keys were inserted.
od = OrderedDict([('a', 1), ('b',
2), ('c', 3)]) print(od.keys()) print(od.values()) print(od.items())
Output:
odict_keys([‘a’, ‘b’, ‘c’]) odict_values([1, 2, 3]) odict_items([(‘a’, 1), (‘b’, 2), (‘c’, 3)])
In this example, we print the keys, values, and key-value pairs in the dictionary.
__reversed__()
The `__reversed__()` method returns an iterator over the keys in reverse order.
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
for key in reversed(od):
print(key)
Output:
b
a
In this example, we iterate over the keys in reverse order.
When to use OrderedDict
The main reason to use an OrderedDict
is when you need to preserve the order of the keys as they are inserted. This is useful in situations where you need to iterate over the keys in a specific order, or where the order of the keys has some meaning.
For example, suppose you are building a web application that allows users to create a custom list of items. You might use an OrderedDict
to store the items in the order in which the user added them to the list, so that you can display them to the user in the same order.
When not to use OrderedDict
In most cases, a standard dictionary will suffice, and you don’t need to use an OrderedDict
. If the order of the keys doesn’t matter, or if you don’t need to iterate over the keys in a specific order, a standard dictionary will work just fine.
Conclusion
In this article, we learned about the OrderedDict
class in Python’s collections
module. We learned how to create an OrderedDict
instance, and we looked at some of the additional methods that are available in OrderedDict
that take advantage of its ordered nature. We also looked at when to use OrderedDict
and when not to use it.
[…] How to use OrderedDict class in Python […]