Last Updated : 14 Jun, 2025
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.
OrderedDict vs dict in PythonNote: 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.
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
Dict
OrdereDdict
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)
dict a 1 b 2 c 3 d 4 ordered dict d 4 b 2 a 1 c 3
Explanation:
Let’s explore some examples to understand how OrderedDict works and see its key features in action.
1. Insertion order preservationOrderedDict 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)
a 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 orderIn 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 orderUnlike 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 orderedDictOrderedDict 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 itempopitem() 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 endWith 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 keysDeleting 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)
a 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 considerationsSuggested Quiz
10 Questions
What is an OrderedDict in Python?
A dictionary that preserves the order of keys
A dictionary that stores data in random order
A list that behaves like a dictionary
A set that stores unique elements in order
What is a key feature of OrderedDict that differentiates it from a standard dict in terms of equality checks?
It ignores the order of keys during comparison
It only compares values for equality
It considers both the keys and their order for equality
It requires keys to be unique for comparison
What method would you use to move a specific key to the end of an OrderedDict?
shift_to_end(key)
move_to_end(key)
push(key)
push_to_back(key)
Which of the following statements is true regarding the performance of OrderedDict compared to standard dict?
OrderedDict is faster for all operations
OrderedDict is slower due to its underlying implementation
Both have the same performance characteristics
OrderedDict is faster only for key retrieval
When using popitem() on an OrderedDict, what does the parameter last=True indicate?
It removes the first item in the OrderedDict
It removes the last item in the OrderedDict
It removes a random item from the OrderedDict
It removes the oldest item based on insertion time
Which module in Python provides the OrderedDict class?
collections
dict
order
ordered_dict
How can you create an OrderedDict from an existing dictionary in Python?
OrderedDict(dict)
dict.OrderedDict()
dict.toOrdered()
OrderedDict.from_dict(dict)
Explanation:
You can directly pass a regular dictionary to OrderedDict() to create an ordered dictionary.
What is the primary data structure used by OrderedDict to maintain the order of keys?
Array
Hash table
Doubly linked list
Stack
What happens when you assign a new value to an existing key in an OrderedDict?
The order of the key is preserved, and its value is updated
The key is moved to the end
The key is removed and re-inserted at the end
The order of keys is reset
What will the following code output?
from collections import OrderedDict
d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
d.move_to_end('b', last=False)
for key, value in d.items():
print(key, value)
a 1, c 3, b 2
a 1, b 2, c 3
c 3, b 2, a 1
Quiz Completed Successfully
Your Score : 2/10
Accuracy : 0%
Login to View Explanation
1/10 1/10 < Previous Next >RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4