OrderedDict in Python with Examples

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

OrderedDict is a class available in the Collections module in Python. It is a subclass of dict.

Example of Counter in Python

from collections import OrderedDict

print(issubclass(OrderedDict, dict))

Output

True

In addition to doing everything a typical dictionary does, the OrderedDict also saves the order of items that are being added to the dictionary.

We can use the OrderedDict to keep track of the order in which the items are added to the dictionary.

Creating an OrderedDict

To create an OrderedDict, we need to import the OrderedDict class from the collections module. To do that, we can use the following line of code.

Example of importing the OrderedDict in Python

from collections import OrderedDict

We can create OrderedDict objects by using the imported class. To create an OrderedDict object, we use the following syntax.

Syntax

OrderedDict([items])

Example of using OrderedDict in Python

from collections import OrderedDict
students = OrderedDict()
students["Name"] = "Michelle"
students["ID"] = 19210293
students["Branch"] = "Computer Science"

print(students)

Output

OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293), (‘Branch’, ‘Computer Science’)])

In the above code example, we can see that the order of items is exactly to same as the order that we defined them,

Modifying the order of items in an OrderedDict

OrderedDict class has the method move_to_end() defined specifically to modify the order of items.

The move_to_end() method takes the key of an item as its arguments and moves it either to the end of the dictionary or to the start of the dictionary depending on the second argument.

The second argument can either be True or False. Passing True moves the passed key to the end and passing False moves the passed key to the start of the dictionary.

If no second argument is passed, it by default moves the passed key to the end of the dictionary.

We can use the following syntax to use this method

Syntax

move_to_end(key, last=True)

Example of using move_to_end() in Python

from collections import OrderedDict
students = OrderedDict()
students["Name"] = "Michelle"
students["ID"] = 19210293
students["Branch"] = "Computer Science"
print(students)

students.move_to_end("ID")
print(students)

students.move_to_end("ID", False)
print(students)

Output

OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293), (‘Branch’, ‘Computer Science’)])OrderedDict([(‘Name’, ‘Michelle’), (‘Branch’, ‘Computer Science’), (‘ID’, 19210293)])

OrderedDict([(‘ID’, 19210293), (‘Name’, ‘Michelle’), (‘Branch’, ‘Computer Science’)])

Defining an Existing Key in OrderedDict

When we try to define an existing key again, the orderedDict replaces the previous value of that key with the newly defined value of that key. The key remains at the same position it was first defined. It has no effect on the order of elements.

Example of using OrderedDict in Python

from collections import OrderedDict
students = OrderedDict()
students["Name"] = "Michelle"
students["ID"] = 19210293
students["Branch"] = "Computer Science"
print(students)

students["ID"] = 1612242509
print(students)

Output

OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293), (‘Branch’, ‘Computer Science’)])OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 1612242509), (‘Branch’, ‘Computer Science’)])

Deleting an Item in OrderedDict

Python provides two methods to delete an item.

popitem(last=True)

We use this method to delete either the last or the first item of an OrderedDict. Passing True to the method or passing no argument deletes the last item and passing False deletes the first item of the OrderedDict. It returns the deleted item.

Example of using popitem() in Python

from collections import OrderedDict
students = OrderedDict()
students["Name"] = "Michelle"
students["ID"] = 19210293
students["Branch"] = "Computer Science"
print(students)

print(students.popitem()) # Deleted the last item
print(students)

print(students.popitem(False)) # Deleting the first item
print(students)

Output

OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293), (‘Branch’, ‘Computer Science’)])
(‘Branch’, ‘Computer Science’)
OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293)]) (‘Name’, ‘Michelle’)
OrderedDict([(‘ID’, 19210293)])

pop(key)

This method takes the key that we want to delete as an argument and delete the item of the passed key. It returns the value of the deleted item.

Example of using pop() in Python

from collections import OrderedDict
students = OrderedDict()
students["Name"] = "Michelle"
students["ID"] = 19210293
students["Branch"] = "Computer Science"
print(students)

print(students.pop('ID'))
print(students)

Output

OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293), (‘Branch’, ‘Computer Science’)])
19210293
OrderedDict([(‘Name’, ‘Michelle’), (‘Branch’, ‘Computer Science’)])

Reinserting a Deleted Item

When we delete an item and then reinsert the deleted item. The reinserted item is then placed at the end of the OrderedDict.

Example of reinserting a deleted item in Python

from collections import OrderedDict
students = OrderedDict()
students["Name"] = "Michelle"
students["ID"] = 19210293
students["Branch"] = "Computer Science"
print(students)

students.pop('ID') # deleting the second item
print(students)

students["ID"] = 19210293 # Reinserting the deleted item
print(students)

Output

OrderedDict([(‘Name’, ‘Michelle’), (‘ID’, 19210293), (‘Branch’, ‘Computer Science’)])
OrderedDict([(‘Name’, ‘Michelle’), (‘Branch’, ‘Computer Science’)])
OrderedDict([(‘Name’, ‘Michelle’), (‘Branch’, ‘Computer Science’), (‘ID’, 19210293)])

Normal Dictionary vs OrderedDict in Python

A normal dictionary is a built-in dictionary that can be created using the dict() function. We don’t need to import any module to define a normal dictionary whereas to define an OrderedDict, we need to import the collections module and use the OrderedDict() function.

The most notable distinction is that an OrderedDict is concerned with order of items, but a regular dictionary is not. Let’s take a closer look at this in the following example.

Example of importance of order in an OrderedDict vs Normal Dictionary

Let us define two normal dictionaries with the same items but in different order and check if those two dictionaries are the same or not.

Example of normal dictionaries in Python

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict2 = {'c':3, 'a': 1, 'd': 4, 'b': 2}
print(dict1 == dict2)

Output

True

In the above code, although the order of items is different, Python still interpreted the both dictionaries as equal.

Let us define two OrderedDicts with the same items but in different order and check if those two OrderedDicts are the same or not.

Example of OrderedDicts in Python

from collections import OrderedDict
ordered_dict1 = OrderedDict()
ordered_dict1['a'] = 1
ordered_dict1['b'] = 2
ordered_dict1['c'] = 3
ordered_dict1['d'] = 4

ordered_dict2 = OrderedDict()
ordered_dict2['c'] = 3
ordered_dict2['a'] = 1
ordered_dict2['d'] = 4
ordered_dict2['b'] = 2

print(ordered_dict1 == ordered_dict2)

Output

False

In the above code example, since the order of items is different and we used OrderedDicts, Python interpreted that both the dictionaries are different and not equal.

Python Interview Questions on OrderedDict

Q1. Write a program to create the following OrderedDict: OrderedDict([(‘Michael’, ‘Pass’), (‘Franklin’, ‘Fail’), (‘Trevor’, ‘Fail’), (‘Luis’, ‘Pass’)])

Ans 1. Complete code is as follows:

from collections import OrderedDict
odict = OrderedDict()

odict['Michael'] = 'Pass'
odict['Franklin'] = 'Fail'
odict['Trevor'] = 'Fail'
odict['Luis'] = 'Pass'

print(odict)

Output

OrderedDict([(‘Michael’, ‘Pass’), (‘Franklin’, ‘Fail’), (‘Trevor’, ‘Fail’), (‘Luis’, ‘Pass’)])

Q2. Complete the following code to remove the first two items from the OrderedDict.

from collections import OrderedDict
a = {1: 3, 2: 4, 3: 5, 4: 6}
odict = OrderedDict(a)

# Your code here

print(odict)

Ans 2. Complete code is as follows:

from collections import OrderedDict
a = {1: 3, 2: 4, 3: 5, 4: 6}
odict = OrderedDict(a)

# Your code here
odict.popitem(last=False)
odict.popitem(last=False)

print(odict)

Output

OrderedDict([(3, 5), (4, 6)])

Q3. Write a program to move the items with keys “Population”, and “GDP” in the dictionary {‘Population’: 39_70_000, ‘GDP’: 819_446_415, ‘Country’: ‘USA’, ‘State’: ‘California’, ‘City’: ‘Los Angeles’} to the end of the dictionary.

Ans 3. Complete code is as follows:

from collections import OrderedDict
a = {'Population': 39_70_000, 'GDP': 819_446_415, 'Country': 'USA', 'State': 'California', 'City': 'Los Angeles'}
odict = OrderedDict(a)

odict.move_to_end('Population')
odict.move_to_end('GDP')

print(odict)

Output

OrderedDict([(‘Country’, ‘USA’), (‘State’, ‘California’), (‘City’, ‘Los Angeles’), (‘Population’, 3970000), (‘GDP’, 819446415)])

Q4. Write a program to move the items with keys “p”, and “q” in the dictionary {‘r’: 3, ‘p’: 2, ‘q’: 1} to the end of the dictionary.

Ans 4. Complete code is as follows:

from collections import OrderedDict
a = {'r': 3, 'p': 2, 'q': 1}
odict = OrderedDict(a)

odict.move_to_end('q', last=False)
odict.move_to_end('p', last=False)

print(odict)

Output

OrderedDict([(‘p’, 2), (‘q’, 1), (‘r’, 3)])

Q5. Write a program to remove the item (4, ‘c’) from the OrderedDict {‘a’: 1, ‘b’: 3, 4: ‘c’, ‘d’: 5}.

Ans 5. Complete code is as follows:

from collections import OrderedDict
a = {'a': 1, 'b': 3, 4: 'c', 'd': 5}
odict = OrderedDict(a)

odict.pop(4)

print(odict)

Output

OrderedDict([(‘a’, 1), (‘b’, 3), (‘d’, 5)])

Conclusion

In this article, we learned about the OrderedDict and how it is different from a normal dictionary. We also learned various useful methods that we can use on OrderedDicts. Furthermore, please feel free to leave any questions in the comments section.

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


1 Response

  1. Andy says:

    Answer 4, shouldn’t that be (Python 3):

    from collections import OrderedDict
    a = {‘r’: 3, ‘p’: 2, ‘q’: 1}
    odict = OrderedDict(a)

    odict.move_to_end(‘q’)
    odict.move_to_end(‘p’)
    print(odict)

Leave a Reply

Your email address will not be published. Required fields are marked *