PYTHON
Preserving Dictionary Order with `OrderedDict`
Learn to maintain the insertion order of key-value pairs in a dictionary using Python's `collections.OrderedDict`, useful for specific API requirements or form processing.
from collections import OrderedDict
# Simulating ordered form submission data
form_data = OrderedDict()
form_data['username'] = 'john.doe'
form_data['email'] = '[email protected]'
form_data['password'] = 'securepass123'
form_data['age'] = 30
print("Ordered Form Data:")
for key, value in form_data.items():
print(f" {key}: {value}")
# Example: Reordering keys in an existing dictionary
regular_dict = {'b': 2, 'a': 1, 'c': 3}
ordered_dict_from_items = OrderedDict(sorted(regular_dict.items()))
print("
Ordered Dict from sorted items:")
for key, value in ordered_dict_from_items.items():
print(f" {key}: {value}")
# Example output:
# Ordered Form Data:
# username: john.doe
# email: [email protected]
# password: securepass123
# age: 30
#
# Ordered Dict from sorted items:
# a: 1
# b: 2
# c: 3
How it works: Prior to Python 3.7, standard `dict`s did not guarantee insertion order. `collections.OrderedDict` was the solution to maintain the order in which items were inserted, making it crucial for scenarios like serialization where order matters. While modern Python `dict`s now preserve insertion order, `OrderedDict` explicitly communicates this intent and remains useful for compatibility with older Python versions or when stricter guarantees about order (e.g., equality testing considers order) are needed.