Python

Usage of Python OrderedDict Example

Here we will see how to work with the Python OrderedDict collection.

This article is intended for the users, who are using Python 3.6 or lower versions because of Python 3.7, a new improvement to the built-in dict the release doc says:

The insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

Hence, there is no real need of OrderedDict anymore for new Python users concerning maintaining the order; while considering some minor differences.

Python OrderedDict:

The OrderedDict is a subclass of Python Dict, it stores the elements, the way they get inserted into it. In a normal Python Dict data structure, we can not expect the order of the elements in which we inserted. Whereas the OrderedDict preserves the order.

Python OrderedDict Example:

Let’s create an OrderedDict and do some operations on it.

from collections import OrderedDict

ord_dict = OrderedDict()
ord_dict['A'] = 65
ord_dict['B'] = 66
ord_dict['C'] = 67
ord_dict['D'] = 68

for key, value in ord_dict.items():
    print(f"{key} => {value}")

Output:

A => 65
B => 66
C => 67
D => 68

In the above output, you can observe the order of the elements, it was read as we inserted it into OrderedDict.

Reverse OrderedDict:

We can reverse the order of OrderedDict while reading it using reversed()function.

from collections import OrderedDict

ord_dict = OrderedDict()
ord_dict['A'] = 65
ord_dict['B'] = 66
ord_dict['C'] = 67
ord_dict['D'] = 68

print("Reverse Order")
for key, value in reversed(ord_dict.items()):
    print(f"{key} => {value}")

Output:

Reverse Order
D => 68
C => 67
B => 66
A => 65

Convert Dict to OrderedDict:

A normal python Dict can easily be converted to OrderdDict like the following.

data = {"online": 6, "tutorials":9, "point":5}

print("Before Ordered")
print(data)

print("After Ordered")
print(OrderedDict(data))

Output:

Before Ordered
{'online': 6, 'tutorials': 9, 'point': 5}
After Ordered
OrderedDict([('online', 6), ('tutorials', 9), ('point', 5)])

As I mentioned earlier there is no difference in results for Dict or OrderedDicteither; while we use Python 3.7 or later versions.

Done!

References:

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Python

Python List comprehension usage and advantages

In this tutorial, we'll learn all about List Comprehension in Python, what advantages it gives over the traditional alternatives. Let's start with the definition of list comprehension. What…

Ask a question or leave a comment