OrderedDict is a subclass of Python's built-in dictionary dict that remembers the order in which keys are inserted. Unlike older versions of Python where dictionaries did not guarantee order, OrderedDict preserves insertion order reliably.
Note: From Python 3.7 onwards, the built-in dict also preserves insertion order as an official language feature. So, OrderedDict is mainly useful if you:
- Work with Python versions before 3.7.
- Need extra features like reordering keys or popping items in LIFO/FIFO order.
OrderedDict vs dict in Python
Understanding OrderedDict and dict is important since both preserve insertion order (dict since Python 3.7), but OrderedDict offers extra features like key reordering and popping items from either end, giving more control. See the comparison table below for clarity.
Feature | OrderedDict | dict |
---|
Maintains insertion order | Yes | Yes |
---|
Allows key reordering | No | Yes (move_to_end(key, last=True)) |
---|
Pop items from ends | No (only popitem() removes last item) | Yes (popitem(last=True/False)supports both ends) |
---|
Equality check considers order | No (order ignored) | Yes (order matters) |
---|
Performance | Faster | Slightly slower |
---|
Example:
Python
from collections import OrderedDict
print("dict")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
for key, val in d.items():
print(key, val)
print("ordered dict")
od = OrderedDict()
od['d'] = 4
od['b'] = 2
od['a'] = 1
od['c'] = 3
for key, val in od.items():
print(key, val)
Outputdict
a 1
b 2
c 3
d 4
ordered dict
d 4
b 2
a 1
c 3
Explanation:
- First part creates a regular dictionary d, adds keys in order and prints them, showing insertion order .
- Second part creates an OrderedDict od with keys added in a different order and prints them, preserving that order exactly.
Examples & key features
Let’s explore some examples to understand how OrderedDict works and see its key features in action.
1. Insertion order preservation
OrderedDict maintains the sequence exactly as elements were added. This is particularly useful in applications such as JSON serialization, form field processing or displaying logs, where the order of items carries semantic meaning.
Python
from collections import OrderedDict
d = {'a': 1, 'b': 2, 'c': 3}
for k, v in d.items():
print(k, v)
print("OrderedDict:")
od = OrderedDict([('d', 4), ('b', 2), ('a', 1), ('c', 3)])
for k, v in od.items():
print(k, v)
Outputa 1
b 2
c 3
OrderedDict:
d 4
b 2
a 1
c 3
Explanation: This code creates a regular dictionary d and prints its items in insertion order. Then, it creates an OrderedDict od with keys in a different order and prints them, showing how OrderedDict preserves the exact insertion sequence.
2. Changing value does not affect order
In an OrderedDict, modifying the value of an existing key does not change its position in the order. This means you can update the values without affecting the original key order.
Python
from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
od['c'] = 5
for k, v in od.items():
print(k, v)
Explanation: This code creates an OrderedDict od with keys 'a', 'b', 'c', and 'd'. It then updates the value of the key 'c' to 5. When printing, the keys remain in their original order, showing that changing a value does not affect the key order in an OrderedDict.
3. Equality checks consider order
Unlike regular dicts, OrderedDict checks both content and order for equality, so differing orders make them unequal. This is useful when order matters.
Python
from collections import OrderedDict
od1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
od2 = OrderedDict([('c', 3), ('b', 2), ('a', 1)])
print(od1 == od2)
Explanation: This code creates two OrderedDicts od1 and od2, with the same keys and values but in different orders. When comparing them, the result is False because OrderedDicts consider both the content and the order of keys for equality.
4. Reversing an orderedDict
OrderedDict doesn’t have a built-in .reverse() method, but you can reverse its order by using Python’s reversed() function on list(od.items()). Creating a new OrderedDict from this reversed list preserves the reversed order.
Python
from collections import OrderedDict
d1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
d2 = OrderedDict(reversed(list(d1.items())))
for k, v in d2.items():
print(k, v)
Explanation: This code creates an OrderedDict d1 with keys 'a', 'b', and 'c'. It then reverses the order of d1’s items using reversed() and creates a new OrderedDict d2 with this reversed order.
5. Pop last or first item
popitem() in OrderedDict removes the last item if last=True (default) or the first if last=False, making it useful for stacks and queues.
Python
from collections import OrderedDict
d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
res = d.popitem(last=True) # Remove last inserted item
print(res)
Explanation: This code removes and returns the last item ('c', 3) from the OrderedDict using popitem(last=True).
6. Move keys to front or end
With the move_to_end() method, OrderedDict provides the flexibility to reposition keys. You can push a specific key to the beginning or end of the dictionary without deleting and re-inserting it.
Python
from collections import OrderedDict
d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
d.move_to_end('a') # Move 'a' to end
d.move_to_end('b', last=False) # Move 'b' to front
for k, v in d.items():
print(k, v)
Explanation: This code moves the key 'a' to the end of the OrderedDict and moves 'b' to the front. When printed, the keys appear in the order: 'b', 'c', 'a'.
7. Deleting and re-inserting keys
Deleting and re-inserting a key in an OrderedDict moves it to the end, preserving insertion order useful for tracking recent actions or updating featured items.
Python
from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
od.pop('c') # Delete 'c'
for k, v in od.items():
print(k, v)
od['c'] = 3 # Re-insert 'c' at end
for k, v in od.items():
print(k, v)
Outputa 1
b 2
d 4
a 1
b 2
d 4
c 3
Explanation: This code deletes the key 'c' from the OrderedDict, then prints the remaining items. After that, it re-inserts 'c' with its value at the end and prints all items again.
Other considerations
- In Python 2.7, OrderedDict uses more memory than a normal dict due to its doubly linked list implementation.
- OrderedDict in Python 2.7 is not a subclass of dict but a specialized container from the collections module.
- From Python 3.7 onwards, regular dicts guarantee insertion order.
- popitem method in OrderedDict allows it to be used like a stack, enabling implementations like an LRU cache.
Similar Reads
Python Collections Module
The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
12 min read
Namedtuple in Python
Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple.What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provid
8 min read
Deque in Python
A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.E
6 min read
ChainMap in Python
Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: Python3 # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6}
3 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
6 min read
OrderedDict in Python
OrderedDict is a subclass of Python's built-in dictionary dict that remembers the order in which keys are inserted. Unlike older versions of Python where dictionaries did not guarantee order, OrderedDict preserves insertion order reliably.Note: From Python 3.7 onwards, the built-in dict also preserv
7 min read
Defaultdict in Python
In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.Key Features of defaultdict:When we access a key that doesn'
6 min read
Collections.UserDict in Python
An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
2 min read
Collections.UserList in Python
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
2 min read
Collections.UserString in Python
Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: Python3 # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World'
2 min read