What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

OrderedDict in Python: What is Ordered Dictionary? (with code)

  • Apr 06, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Komal Gupta
OrderedDict in Python: What is Ordered Dictionary? (with code)

If you're a Python developer, you're undoubtedly working with dictionaries a lot. It enables the storage of key-value combinations. This is where you need to learn about Ordered Dictionary in Python, including its utilization, initialization, methods, and time complexity. So, without any further delay, let's get started.

What is OrderedDict in Python?

OrderedDict in Python is a dictionary-like container that not only performs standard dictionary functions but also includes some new methods such as move_to_end() and an improved popitem() method for reordering and removing items from either side of the inputted dictionary.

In a way, it maintains the order in which keys were originally inserted and remembers the order in which the items were added, and iterates over them in that order when their elements are accessed. 

OrderDict is a subclass of dictionaries added in Python 3.1 as a standard library to use under the collection module. Here is how to implement it with code:

import collections
from collections import OrderedDict as od

 

Is OrderedDict obsolete?

No, OrderedDict() is still relevant and useful in Python, particularly when the order of the elements in a dictionary must be maintained.  Although a built-in dictionary class has been guaranteed to maintain the order of insertion since Python 3.6, the use of OrderedDict() can still be beneficial in some cases.

It can be used for codebases running on Python versions older than 3.6 using the ordereddict() method to order a dictionary item which may break down if we change it to a regular dictionary also ordereddict() has sole additional functions which are not available in dict class.

Ordered vs Regular Dictionary

The natural issue that may arise is when we should use an OrderedDict over a regular Dict. Isn't it obvious that since an OrderedDict maintains item order, we should always use it?

The answer is a little tricky because keeping the order of a dictionary comes at a cost, namely OrderedDict() needs 50% more memory storage. It is also more complex than a regular dictionary because of its ability to keep order, which necessitates an extra hop on the additional data structure.

As a result, you should always use the most appropriate dictionary type for the job at hand.

What is the Complexity of OrderedDict?

The time complexity of Python's OrderedDict is O(1) for the average case and O(n) for the worst case, which is the same as that of a regular dictionary. The implementation abstracts, or masks, a doubly-linked list for tracking insertion sequence. It is, however, a little slower in performance is slightly slower because it has the additional overhead of maintaining the order.

Python's OrderDict Examples

Now, we will look at some of the examples and common problems with Ordered Dictionary in Python:

Creating Instance of OrderedDict class

Creating an empty OrderedDict() instance and directly passing key-value pairs to the dictionary. 

import collections
from collections import OrderedDict as od
odict = od() # Instance of class OrdereDict
odict[1]='Python'
odict[2]='Learning'
odict[3]='Tutorial'
 
print(odict)

 

Output:

OrderedDict([(1, 'Python'), (2, 'Learning'), (3, 'Tutorial')])

 

Maintaining OrderedDict for the list of tuples

Here is the code t maintain the list of tuples in ordered dictionary inputted by the user:

import collections
from collections import OrderedDict as od
# taking a list as input 
l=eval(input("Enter the list of tuples"))
'''User input --> [(1,'Python'), (2,'Blog'), (3,'on '), (4,'Ordered Dictionary')]'''
# Passing the list to ordereddict instance
odict = od(l) 
print(odict)

 

Output:

OrderedDict([(1, 'Python'), (2, 'Blog'), (3, 'on '), (4, 'Ordered Dictionary')])

 

We can also use keyword arguments:

import collections
from collections import OrderedDict as od
odict = od(Monday=1,Tuesday=2,Wednesday=3,Thursday=4,Friday=5,Saturday=6,Sunday=7)
print(odict)

 

Output:

OrderedDict([('Monday', 1), ('Tuesday', 2), ('Wednesday', 3), ('Thursday', 4), ('Friday', 5), ('Saturday', 6), ('Sunday', 7)])

 

Another common problem you might see is changing the order of removal. OrderedDict popitem() function removes the items in the FIFO order. It accepts a boolean argument last, if it’s set to True then items are returned in LIFO order.

from collections import OrderedDict

# Initializing an OrderedDict
od = OrderedDict([('Favtutor', 1), ('Python', 2), ('Live', 3), ('Training', 4), ('Sessions', 5)])
print("Inputted Dict",od)
print("-------------------------------------------------------")
# Accessing elements
print("keys:",od.keys())
print("values:",od.values())
print("Items:",od.items())
print("-------------------------------------------------------")
# Adding elements
od.update({'Join Now': 6})
od['Enjoy'] = 7
print("Updated dict",od)
print("-------------------------------------------------------")
# Removing elements

b=od.pop('Enjoy')
print("Removing the",b)
# od.popitem()
print("Updated dict",od)
print("-------------------------------------------------------")

# Reordering elements
od.move_to_end('Python')
print(od)
print("-------------------------------------------------------")

# Copying
od2 = od.copy()
od3 = dict(od)

print("copy dict",od3)
print("-------------------------------------------------------")

# Equality and comparison
od4 = OrderedDict([('Python', 2), ('Training', 4), ('Session', 5)])
print("comparing OD and OD2",od == od2)
print("-------------------------------------------------------")
# Clearing
od.clear()
print(od)
print("-------------------------------------------------------")

 

Output :

Inputted Dict OrderedDict([('Favtutor', 1), ('Python', 2), ('Live', 3), ('Training', 4), ('Sessions', 5)])
-------------------------------------------------------
keys: odict_keys(['Favtutor', 'Python', 'Live', 'Training', 'Sessions'])
values: odict_values([1, 2, 3, 4, 5])
Items: odict_items([('Favtutor', 1), ('Python', 2), ('Live', 3), ('Training', 4), ('Sessions', 5)])
-------------------------------------------------------
Updated dict OrderedDict([('Favtutor', 1), ('Python', 2), ('Live', 3), ('Training', 4), ('Sessions', 5), ('Join Now', 6), ('Enjoy', 7)])
-------------------------------------------------------
Removing the 7
Updated dict OrderedDict([('Favtutor', 1), ('Python', 2), ('Live', 3), ('Training', 4), ('Sessions', 5), ('Join Now', 6)])
-------------------------------------------------------
OrderedDict([('Favtutor', 1), ('Live', 3), ('Training', 4), ('Sessions', 5), ('Join Now', 6), ('Python', 2)])
-------------------------------------------------------
copy dict {'Favtutor': 1, 'Live': 3, 'Training': 4, 'Sessions': 5, 'Join Now': 6, 'Python': 2}
-------------------------------------------------------
comparing OD and OD2 True
-------------------------------------------------------
OrderedDict()
-------------------------------------------------------

 

How to iterate over the OrderedDict?

We can go through the ordered dictionary using the items function. The view object is returned by the.items() function as a list of tuples of key-value pairs. Furthermore, when the view object is iterated over, tuples of Key-value pairs are produced.

Here is an example:

import collections
from collections import OrderedDict as od
odict = od(Monday=1,Tuesday=2,Wednesday=3,Thursday=4,Friday=5,Saturday=6,Sunday=7)
for key,value in odict.items():
    print(odict[key],key)

 

Output:

1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday

 

We can also use keypairs, using the code:

import collections
from collections import OrderedDict as od
odict = od(Monday=1,Tuesday=2,Wednesday=3,Thursday=4,Friday=5,Saturday=6,Sunday=7)
for key in odict:
    print(odict[key],key)

 

Output :

1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday

 

Conclusion

We learned everything about Python's POrderedDict subclass that is used to keep the key-value pairs in order with examples and code. The order in which things are stored corresponds to the order in which they are inserted. When an item is updated, it is done in place. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Komal Gupta
I am a driven and ambitious individual who is passionate about programming and technology. I have experience in Java, Python, and machine learning, and I am constantly seeking to improve and expand my knowledge in these areas. I am an AI/ML researcher. I enjoy sharing my technical knowledge as a content writer to help the community.