Things To Know About Python OrderedDict | collections.OrderedDict

So, you want to learn about collections.OrderedDict, take a seat. You are at the right place. OrderedDict, a dictionary subclass, introduced in python’s version 3.1 to the standard library. It is a part of python’s collection module.

It was an addition to the collection module due to the fact that the built-in dict class didn’t keep the order in which items were inserted.

Note: Since the release of Python 3.6, the dictionary data type can keep the order of items in which they were inserted. It should be noted ordered dict is still in use.

OrderedDict, yet another dictionary?

Thus, one would question the need for another dictionary in python. The built-in dict class solved the issue of the order(in version 3.6), which had prompted ordered dict introduction in the first place.

As a result, it all boils down to what you are trying to achieve or do.

  • Python’s codebases that are still running versions older than 3.6 and using ordereddict to order the items of dicitonary, might breakdown if regular dictionary is used. Hence, collections.ordereddict has to be still used.
  • OrderedDict has all the functionalities that a regular dicitonary has to offer. Moreover, it has other extra methods like move_to_end() for reordering the items and an enhanced popitem() method which can remove items from either end of dicitonary.

With this in mind, we will try to bring out the nuances present and establish the need for OrderedDict in the upcoming sections of this article. You can also check out the collection module’s functions from here.

Importing OrderedDict

# using as collections.OrderedDict
import collection

# direct usage
from collections import OrderedDict

Creating an OrderedDict

Following are the ways through which one could create an ordered dictionary.

1. Creating an instance, populating after

OrderedDict takes in key-value pairs and creates an ordered dictionary out of it. After importing the collections.OrderedDict, create an object of OrderedDict, then pass values into it.

from collections import OrderedDict

odict = OrdereDict()
odict[1]='a'
odict[2]='b'
odict[3]='c'

print(odict)
Ordereddict Instantiating first and providing key-value pairs afterwards
Instantiating first and providing key-value pairs afterward

2. Passing an a list of tuples

You can simply pass key-value pairs directly into [()], like so:

from collections import OrderedDict

odict = OrderedDict([(1,'a'), (2,'b'), (3,'c'), (4,'d')])
print(odict)
Creating collections.ordereddict by passing list of tuples
Creating collections.ordereddict by passing list of tuples

3. Using a regular dictionary

from collections import OrderedDict

odict = OrderedDict({'monday':1, 'tuesday':2, 'wednesday':3,'thrusday':4,'friday':5,'saturday':6,'sunday':7})
print(odict)
Creating collections.ordereddict by passing a regular dictionary
Creating collections.ordereddict by passing a regular dictionary

Note: The order will not be maintained if a version older than python 3.6 is used for creating collections.OrderedDict on passing a dictionary.

4. Using keyword arguments

You can very quickly populate collections ordereddict by using keyword arguments as key-value pairs. Let’s look how:

from collections import OrderedDict

odict = OrderedDict(maths=1, physics=2, chemistry=3, hindi=4, english=5)
print(odict)
OrderedDict using keyword argument
OrderedDict using keyword argument

Iterating over an OrderedDict

Let’s see various ways to iterate over collections.OrderedDict:

weeks_dict = OrderedDict({'monday':1, 'tuesday':2, 'wednesday':3,'thrusday':4,'friday':5,'saturday':6,'sunday':7})

Example 1: Iterating using keys

for key in weeks_dict:
    print(key.capitalize(), weeks_dict[key])

The above code is concise and straightforward. It simply takes a key from the weeks_dict and then, using the same key, generates its corresponding value.

Ouput of example 1
Output, iteration using keys

Example 2: Iterating using .items()

for key, value in weeks_dict.items():
    print(key.capitalize(), value)

The .items() method returns a list of tuples of key-value pairs, called the view object. Moreover, tuples of Key-value pairs are generated when the view object is iterated over.

Output, iterating using .items()
Output, iterating using .items()

Example 3: Iterate in reverse order

for key, value in reversed(weeks_dict.items()):
print(key.capitalize(), value)

The reversed() function, as the name clearly suggests, is used to iterate over collections.OrderedDict in reverse order. However, after the inclusion of the ordering feature in dict class, it can too iterate in reversed order.

Output, iterating in reverse order
Output, iterating in reverse order.

Functions of OrderedDict

Ordereddict has all the functions or tools that a regular dictionary has to offer. Moreover, it provides additional functions like move_to_end() and popitem(). Let’s discuss them:

move_to_end()

OrderedDict has a useful method i.e. .move_to_end(). This method allows rearranging existing items. Furthermore, it can reorder items to either start or at the end of the dictionary.

Let’s look at its parameters:

key: Key of the item you want to reorder.

last: It is a boolean value. The default value is set True, indicating the item will be moved to the end, while if the last is set to False, it will be moved to the beginning of the ordered dict.

Moving item to the end

from collections import OrderedDict

weeks_dict = OrderedDict({'monday':1, 'tuesday':2, 'wednesday':3,'thrusday':4,'friday':5,'saturday':6,'sunday':7})

weeks_dict.move_to_end('monday')
print(weeks_dict)
Output of move_to_end() method
The output of move to end method, move to end

Moving item to the beginning

weeks_dict.move_to_end('sunday',False)
print(weeks_dict)
The output of the move_to_end() method, moved to start
The output of the move to end method, move to begin

popitem()

The pop item method takes a single argument which is last. It defaults to True. If True, the pop item method removes and returns the item from the end(LIFO order), while if set to False, it removes and returns the item from the beginning(FIFO order).

Removing from the end

from collections import OrderedDict

weeks_dict = OrderedDict({'monday':1, 'tuesday':2, 'wednesday':3,'thrusday':4,'friday':5,'saturday':6,'sunday':7})

weeks_dict.popitem()
print(weeks_dict)
popitem method removes items from the end.
pop item method removes items from the end.

Removing from the start

weeks_dict.popitem(False)
print(weeks_dict)
popitem() remove from the start
pop item method removes an item from the start.

OrderedDict Vs Dictionary

Although, since python’s version 3.6 dictionary is able to keep the order of items, however ordered dict is more order-sensitive. Let’s look at some examples.

Ordereddict maintain the order
Ordered dict maintain the order.

Performance

The implementation of the ordered dict abstracts or in other words, hides a doubly-linked list for tracking the order of insertion. However, this increases some memory usage.

The insertion operation is O(1). However, deleting a key-value pair requires the key to be searched. This adds a little overhead. Nonetheless, the actual deletion requires O(1) time complexity. Notably, a list requires O(n) to search the item and O(n) to remove the key.

Accessing item using index

Method 1: using items method

import collections 

test_dict = collections.OrderedDict()
test_dict['January'] = 1
test_dict['Febuary'] = 2
test_dict['March'] = 3

items = list(test_dict.items())

print(items[0])
print(items[1])
print(items[2])

Let’s breakdown the code above:

  • Firstly, we create a list of tuples of key-value pairs.
  • As a result, we can index items of test_dict.
Indexing using items method
Indexing using items method

Method 2: using islice method

You can avoid extra memory usage using the itertools islice method.

import collections 

test_dict = collections.OrderedDict()
test_dict['January'] = 1
test_dict['Febuary'] = 2
test_dict['March'] = 3

print(next(islice(test_dict.items(),0,1)))
print(next(islice(test_dict.items(),1,2)))
print(next(islice(test_dict.items(),2,3)))
Indexing using islice method
Indexing using islice method

Ordered dict comprehension

from collections import OrderedDict

t_dict = OrderedDict((num, num**2) for num in range(6))
print(t_dict)

Let’s understand the code above; while initializing the ordered dict, we have passed a dictionary comprehension code that iteratively takes a number in range as a key and its square as its value.

Ordered dict comprehension
Ordered dict comprehension

FAQs on Python Ordereddict

What are collections Ordered dict?

OrderedDict remembers the order of items in which they are inserted. However, from version 3.6 of python, the regular dictionary now remembers the order.

How to import Ordered dict?

You can easily import OrderedDict using from collections import OrderedDict.

Is Ordered dict required?

It depends on the thing you are trying to do. OrderedDict provides many order-related methods like move_to_end() and an enhanced popitem().

Does Python dict preserve order?

Yes, from version 3.6 python dict class preserves the order of key-value pairs in which they were inserted.

Converting ordered dict to a regular dictionary

>>odict = OrderedDict(maths=1, physics=2, chemistry=3, hindi=4, english=5)
>>dict(odict)

Output: {‘maths’: 1, ‘physics’: 2, ‘chemistry’: 3, ‘hindi’: 4, ‘english’: 5}

Does the has_key method work in ordered dict?

has_key method has been removed from the dict class and ordereddict from python3 onwards.

Conclusion

In this article, we looked at the collections module’s OrderedDict, an alternative to python’s dict class. One would question its relevance after improvements in the regular dictionary from version 3.6. However, ordered dict has some advantages over dict class. For instance, it provides reordering functions like the move to end and pop item method. We use indexing on ordereddict, but we also use comprehension on ordereddict. Hoping you learned something new today.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments