0
0
PythonHow-ToBeginner · 3 min read

How to Create Ordered Dictionary in Python: Syntax and Examples

In Python, you can create an ordered dictionary using collections.OrderedDict, which keeps the order of keys as inserted. Starting from Python 3.7, the built-in dict also preserves insertion order, but OrderedDict offers extra methods for order manipulation.
📐

Syntax

Use OrderedDict from the collections module to create an ordered dictionary. You can initialize it with a list of key-value pairs or another dictionary.

  • OrderedDict(): Creates an empty ordered dictionary.
  • OrderedDict([('key1', value1), ('key2', value2)]): Creates an ordered dictionary with keys in the given order.
python
from collections import OrderedDict

# Create an empty ordered dictionary
d = OrderedDict()

# Create with initial key-value pairs
d2 = OrderedDict([('apple', 1), ('banana', 2), ('cherry', 3)])
💻

Example

This example shows how to create an ordered dictionary, add items, and print keys in the order they were added.

python
from collections import OrderedDict

# Create ordered dictionary with some fruits
fruits = OrderedDict()
fruits['apple'] = 10
fruits['banana'] = 20
fruits['cherry'] = 30

# Print keys in insertion order
for fruit in fruits:
    print(fruit, fruits[fruit])
Output
apple 10 banana 20 cherry 30
⚠️

Common Pitfalls

One common mistake is assuming that the regular dict in Python versions before 3.7 preserves order, which it does not. Also, using OrderedDict methods incorrectly can cause errors.

For example, OrderedDict has a method move_to_end(key) to change order, which dict does not have.

python
from collections import OrderedDict

# Wrong: expecting dict to preserve order in Python < 3.7
regular_dict = {'a': 1, 'b': 2, 'c': 3}
for key in regular_dict:
    print(key)  # Order not guaranteed in older Python versions

# Right: use OrderedDict for guaranteed order
ordered = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
ordered.move_to_end('a')  # Moves 'a' to the end
print(list(ordered.keys()))
Output
a b c ['b', 'c', 'a']
📊

Quick Reference

MethodDescription
OrderedDict()Create an empty ordered dictionary
OrderedDict(iterable)Create ordered dictionary from iterable of key-value pairs
move_to_end(key)Move an existing key to either end (default is right)
popitem(last=True)Remove and return a (key, value) pair; last=True removes last item
keys()Return keys in insertion order
values()Return values in insertion order
items()Return (key, value) pairs in insertion order

Key Takeaways

Use collections.OrderedDict to create dictionaries that remember insertion order.
From Python 3.7+, regular dict preserves insertion order but lacks OrderedDict's extra methods.
Initialize OrderedDict with a list of tuples to set key order explicitly.
Use move_to_end() to reorder keys in an OrderedDict.
Avoid relying on dict order in Python versions before 3.7.