OrderedDict in Python (with Examples)

Python | OrderedDict: In this tutorial, we will learn about the OrderedDict, its creation, and other operations with the help of examples. By IncludeHelp Last updated : June 11, 2023

What is OrderedDict in Python?

An OrderedDict is a special type of Python dictionary in which the order of insertion of key-value pairs is preserved i.e., it remembers the order of the keys in which they are inserted which cannot be done using the regular dictionary.

Creating an OrderedDict

To create an OrderedDict, we need to import it from the collections library and then insert the key-value pairs or simply assign the key-value pairs during the creation of object of OrderedDict.

Import statement

from collections import OrderedDict

Syntax to create OrderedDict

OrderedDict_Name = OrderedDict([(key1, value1), (key2, value2), ...])

Example 1

In the below example, we will create an OrderedDict, insert the key-value pairs and then print them.

# Importing OrderedDict
from collections import OrderedDict

# Creating an OrderedDict
emp = OrderedDict()
emp["id"] = 101
emp["name"] = "John"
emp["age"] = 32

# Printing
print("emp:", emp)
print("Type of emop:", type(emp))

# Pritning key-value pairs
print("\nemp (key-value pairs):")
for key, value in emp.items():
    print(key, value)

Output:

emp: OrderedDict([('id', 101), ('name', 'John'), ('age', 32)])
Type of emop: <class 'collections.OrderedDict'>

emp (key-value pairs):
id 101
name John
age 32

Example 2

In the below example, we will create an OrderedDict and initialize it during the creation of an object.

# Importing OrderedDict
from collections import OrderedDict

# Creating an OrderedDict
emp = OrderedDict([('id', 101), ('name', 'John'), ('age', 32)])

# Printing
print("emp:", emp)
print("Type of emop:", type(emp))

# Pritning key-value pairs
print("\nemp (key-value pairs):")
for key, value in emp.items():
    print(key, value)

Output:

emp: OrderedDict([('id', 101), ('name', 'John'), ('age', 32)])
Type of emop: <class 'collections.OrderedDict'>

emp (key-value pairs):
id 101
name John
age 32

OrderedDict: Key-value Change

If we change the value of a key-value pair of an OrderedDict, the order will remain the same after the change.

Example

In the below example, we are creating an OrderedDict and then updating a value.

# Importing OrderedDict
from collections import OrderedDict

# Creating an OrderedDict
emp = OrderedDict()
emp["id"] = 101
emp["name"] = "John"
emp["age"] = 32

# Pritning key-value pairs
print("\nBefore Updating:")
for key, value in emp.items():
    print(key, value)

# Updating value    
emp["name"] = "Alvin Alexander"

# Pritning key-value pairs
print("\nAfter Updating:")
for key, value in emp.items():
    print(key, value)

Output:

Before Updating:
id 101
name John
age 32

After Updating:
id 101
name Alvin Alexander
age 32

OrderedDict: Deletion and Re-Insertion

If we delete and re-insert the same key in an OrderedDict. It will maintain the order of insertion.

Example

In the below example, we are creating an OrderedDict, removing an item and then re-inserting the item again.

# Importing OrderedDict
from collections import OrderedDict

# Creating an OrderedDict
emp = OrderedDict()
emp["id"] = 101
emp["name"] = "John"
emp["age"] = 32

# Pritning key-value pairs
print("\nBefore Deleting:")
for key, value in emp.items():
    print(key, value)

# Deleting
emp.pop("name")

# Pritning key-value pairs
print("\nAfter Deleting:")
for key, value in emp.items():
    print(key, value)

# Re-Insertion
emp["name"] = "Alvin Alex."

# Pritning key-value pairs
print("\nAfter Re-Inserting:")
for key, value in emp.items():
    print(key, value)

Output:

Before Deleting:
id 101
name John
age 32

After Deleting:
id 101
age 32

After Re-Inserting:
id 101
age 32
name Alvin Alex.

Iterating over an OrderedDict

An OrderedDict dictionary can be iterated just like a regular dictionary using multiple approaches like direct technique, using the dictionary's method .keys(), .values(), and .items(). Consider the below example -

Example

# Importing OrderedDict
from collections import OrderedDict

# Creating an OrderedDict
emp = OrderedDict([("id", 101), ("name", "John"), ("age", 32)])

# Iterating over the keys
# Direct
print("keys (direct method):")
for key in emp:
    print(key)

# Iterating over the keys
# Using keys() method
print("\nkeys (Using keys() method):")
for key in emp.keys():
    print(key)

# Iterating over the values
# Direct
print("\nValues (direct method):")
for value in emp:
    print(emp[value])

# Iterating over the values
# Using values() method
print("\nValues (Using values() method):")
for value in emp.values():
    print(value)

Output

keys (direct method):
id
name
age

keys (Using keys() method):
id
name
age

Values (direct method):
101
John
32

Values (Using values() method):
101
John
32

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.