How to Use OrderedDict in Python: Syntax and Examples
Use
OrderedDict from the collections module to create dictionaries that remember the order items were added. Import it with from collections import OrderedDict, then create an ordered dictionary like od = OrderedDict() and add items as usual.Syntax
The OrderedDict is imported from the collections module. You create an ordered dictionary by calling OrderedDict(). You can add items using assignment like a normal dictionary. The order of keys is preserved in the order you add them.
python
from collections import OrderedDict # Create an empty OrderedDict od = OrderedDict() # Add items od['apple'] = 1 od['banana'] = 2 od['cherry'] = 3
Example
This example shows how OrderedDict keeps the order of items when iterating, unlike a regular dictionary in older Python versions.
python
from collections import OrderedDict # Create an OrderedDict with some items fruits = OrderedDict() fruits['apple'] = 3 fruits['banana'] = 1 fruits['cherry'] = 2 # Print items in order for fruit, count in fruits.items(): print(f"{fruit}: {count}")
Output
apple: 3
banana: 1
cherry: 2
Common Pitfalls
One common mistake is expecting OrderedDict to sort items automatically. It only remembers the order you add items, it does not sort them. Also, in Python 3.7 and later, regular dictionaries keep insertion order, so OrderedDict is mainly useful for older versions or special methods like move_to_end().
python
from collections import OrderedDict # Wrong: expecting automatic sorting od = OrderedDict() od['banana'] = 2 od['apple'] = 1 od['cherry'] = 3 # This will print in insertion order, not sorted order for key in od: print(key) # Right: use sorted() if you want sorted keys for key in sorted(od): print(key)
Output
banana
apple
cherry
apple
banana
cherry
Quick Reference
| Method | Description |
|---|---|
| OrderedDict() | Create a new ordered dictionary |
| od[key] = value | Add or update an item |
| od.items() | Get items in insertion order |
| od.move_to_end(key) | Move an existing key to the end |
| od.popitem(last=True) | Remove and return last or first item |
Key Takeaways
OrderedDict keeps the order items are added, unlike older dicts.
Import OrderedDict from collections with: from collections import OrderedDict.
OrderedDict does not sort items automatically; use sorted() for sorting.
In Python 3.7+, regular dicts keep insertion order, so OrderedDict is less needed.
Use methods like move_to_end() for special order manipulations.