All about OrderedDict in Python
An OrderedDict
is a type of dictionary that preserves the insertion order of elements, which was not guaranteed in Python versions prior to 3.7.
Before Python 3.7, standard dictionaries (dict
) did not guarantee the order of keys. It was in this context that OrderedDict
was born, via the collections
module.
Since Python 3.7, order is preserved even with dict
, but OrderedDict
remains useful in certain specific cases.
It allows for example:
- to sort elements, then store them in a precise order;
- to make strict comparisons on the order of pairs;
- to use specific operations like
move_to_end()
.
Basic Syntax
Here's how to create an OrderedDict
:
from collections import OrderedDict
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
The insertion order is respected, unlike the old dictionaries before Python 3.7.
OrderedDict-Specific Methods
Even though an OrderedDict
behaves like a standard dictionary, it offers some unique methods related to order management: move_to_end()
and popitem()
.
move_to_end()
This method allows you to move a key either to the end (last=True
by default), or to the beginning (last=False
).
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
od.move_to_end('a')
print(od) # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
This is very useful for managing queues, caches, or prioritizing elements for example. 😉
popitem()
For its part, popitem()
removes and returns an element according to its order:
last=True
: removes the last one;last=False
: removes the first one.
od.popitem(last=False) # Removes ('a', 1)
OrderedDict vs dict: What are the differences?
Since Python 3.7, standard dictionaries preserve insertion order, which has largely reduced the need to use OrderedDict.
Let's still make a comparison between the two elements.
Aspect | dict (Python >= 3.7) | OrderedDict |
Order preserved | ✅ Yes | ✅ Yes |
JSON compatible | ✅ Yes | ✅ Yes |
move_to_end() method | ❌ No | ✅ Yes |
popitem() method | ✅ Yes (but order is not controllable) | ✅ Yes |
Main utility | A bit of everything | Specific cases |
Ultimately, OrderedDict
remains useful for order-sensitive algorithms, such as LRU cache, HTML/XML parsing, or priority structures.
Frequently Asked Questions about OrderedDict
Here are the most frequently asked questions when you start with OrderedDict! 😋
Is
OrderedDict
still useful today?
Yes, especially if you're using Python < 3.7 or if you need specific methods like move_to_end()
or popitem(last=False)
, which are absent from classic dictionaries.
Is it slower than a
dict
?
Slightly, but it's really negligible.
How to learn Python perfectly?
Thanks to a Python course (this one is worth testing!).