108. Python's collections.OrderedDict
OrderedDict is a specialized dictionary in Python's collections module that maintains the order in which items are inserted. Unlike a regular dictionary (prior to Python 3.7), which does not guarantee order, OrderedDict guarantees that the order of the keys will be preserved.
Here are some examples of using OrderedDict in Python:
1. Basic Usage of OrderedDict
An OrderedDict behaves like a normal dictionary, but it remembers the order in which items are added.
Copy
from collections import OrderedDict
# Creating an OrderedDict
ordered_dict = OrderedDict()
# Adding items
ordered_dict['first'] = 'apple'
ordered_dict['second'] = 'banana'
ordered_dict['third'] = 'cherry'
print(ordered_dict)Output:
Copy
OrderedDict([('first', 'apple'), ('second', 'banana'), ('third', 'cherry')])The order of the items is preserved as you inserted them.
2. Creating an OrderedDict from a Regular Dictionary
You can create an OrderedDict from a normal dictionary. Starting from Python 3.7+, the regular dict also preserves insertion order, but OrderedDict has additional features like moving elements.
Copy
Output:
Copy
3. Reordering Items
You can reorder the items in an OrderedDict by using methods such as move_to_end.
Copy
Output:
Copy
You can also move items to the beginning by passing last=False:
Copy
Output:
Copy
4. Reversing an OrderedDict
You can reverse the order of items in an OrderedDict using the reversed() function.
Copy
Output:
Copy
5. Using OrderedDict with popitem()
The popitem() method can be used to remove and return the last item (or the first item if last=False is passed) in the OrderedDict.
Copy
Output:
Copy
To pop the first item:
Copy
Output:
Copy
6. OrderedDict with Default Values (Using defaultdict)
OrderedDict can also be combined with other collections, such as defaultdict. This is useful when you want to work with ordered dictionaries that have default values.
Copy
Output:
Copy
7. Comparing OrderedDicts
You can compare two OrderedDict objects to see if they are equal. The comparison checks both the keys and the order.
Copy
Output:
Copy
8. Using OrderedDict as a Queue (FIFO)
You can use an OrderedDict to implement a queue with FIFO (First-In-First-Out) behavior.
Copy
Output:
Copy
9. OrderedDict as an Ordered Key-Value Store
You can store key-value pairs in the OrderedDict and iterate over the keys and values while maintaining the order.
Copy
Output:
Copy
10. Updating an OrderedDict
You can update an OrderedDict using the update() method or using direct assignment.
Copy
Output:
Copy
Key Points:
OrderedDictpreserves the order of insertion, unlike regular dictionaries in older versions of Python (before 3.7).You can reorder items, pop items from the beginning or end, and even reverse the dictionary.
It has some additional methods, such as
move_to_endandpopitem, that make it more flexible compared to regular dictionaries.
Last updated