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.

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:

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.

Output:


3. Reordering Items

You can reorder the items in an OrderedDict by using methods such as move_to_end.

Output:

You can also move items to the beginning by passing last=False:

Output:


4. Reversing an OrderedDict

You can reverse the order of items in an OrderedDict using the reversed() function.

Output:


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.

Output:

To pop the first item:

Output:


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.

Output:


7. Comparing OrderedDicts

You can compare two OrderedDict objects to see if they are equal. The comparison checks both the keys and the order.

Output:


8. Using OrderedDict as a Queue (FIFO)

You can use an OrderedDict to implement a queue with FIFO (First-In-First-Out) behavior.

Output:


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.

Output:


10. Updating an OrderedDict

You can update an OrderedDict using the update() method or using direct assignment.

Output:


Key Points:

  • OrderedDict preserves 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_end and popitem, that make it more flexible compared to regular dictionaries.

Last updated