Wednesday, July 3, 2024
HomeLanguagesPythonOrderedDict in Python

OrderedDict in Python

An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that:

OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.

Python3




# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
 
print("This is a Dict:\n")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
 
for key, value in d.items():
    print(key, value)
 
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
 
for key, value in od.items():
    print(key, value)


Output

This is a Dict:

a 1
b 2
c 3
d 4

This is an Ordered Dict:

a 1
b 2
c 3
d 4

Output: 

This is a Dict:
a 1
b 2
c 3
d 4
This is an Ordered Dict:
a 1
b 2
c 3
d 4

Important Points: 

1. Key value Change: If the value of a certain key is changed, the position of the key remains unchanged in OrderedDict.

Python3




# A Python program to demonstrate working of key
# value change in OrderedDict
from collections import OrderedDict
 
print("Before:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
    print(key, value)
 
print("\nAfter:\n")
od['c'] = 5
for key, value in od.items():
    print(key, value)


Output: 

Before:
a 1
b 2
c 3
d 4
After:
a 1
b 2
c 5
d 4

2. Deletion and Re-Inserting: Deleting and re-inserting the same key will push it to the back as OrderedDict, however, maintains the order of insertion.

Python3




# A Python program to demonstrate working of deletion
# re-insertion in OrderedDict
from collections import OrderedDict
 
print("Before deleting:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
 
for key, value in od.items():
    print(key, value)
 
print("\nAfter deleting:\n")
od.pop('c')
for key, value in od.items():
    print(key, value)
 
print("\nAfter re-inserting:\n")
od['c'] = 3
for key, value in od.items():
    print(key, value)


Output

Before deleting:

a 1
b 2
c 3
d 4

After deleting:

a 1
b 2
d 4

After re-inserting:

a 1
b 2
d 4
c 3

Output: 

Before deleting:
a 1
b 2
c 3
d 4
After deleting:
a 1
b 2
d 4
After re-inserting:
a 1
b 2
d 4
c 3

OrderedDict is a dictionary subclass in Python that remembers the order in which items were added. In a regular Python dictionary, the order of the items is not guaranteed, and it may change between different runs of the program or different versions of Python. However, an OrderedDict preserves the order of the items as they were added, even if new items are later added or existing items are changed.

OrderedDict is part of the collections module in Python. It provides all the methods and functionality of a regular dictionary, as well as some additional methods that take advantage of the ordering of the items. Here are some examples of using OrderedDict in Python:

Python3




from collections import OrderedDict
 
# Create an ordered dictionary of key-value pairs
my_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
 
# Add a new item to the end of the dictionary
my_dict['d'] = 4
 
# Add a new item at a specific position in the dictionary
# my_dict.update({'e': 5, 'f': 6}) or below
my_dict.update([('e', 5), ('f', 6)])
my_dict.move_to_end('e', last=False)
 
# Iterate over the dictionary in the order in which items were added
for key, value in my_dict.items():
    print(key, value)


# Output:
# e 5
# f 6
# a 1
# b 2
# c 3
# d 4

Time Complexity:

  • Get item(Key): O(1)
  • Set item(key, value): O(1)
  • Delete item(key): O(n)
  • Iteration: O(n)

Space Complexity: O(n)

Other Considerations:  

  • Ordered dict in Python version 2.7 consumes more memory than normal dict. This is due to the underlying Doubly Linked List implementation for keeping the order. In Python 2.7 Ordered Dict is not dict subclass, it’s a specialized container from collections module.
  • Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.
  • Ordered Dict can be used as a stack with the help of popitem function. Try implementing LRU cache with Ordered Dict.

This article is contributed by Sri Sanketh Uppalapati. If you like Lazyroar and would like to contribute, you can also write an article using write.neveropen.co.za or mail your article to review-team@neveropen.co.za. See your article appearing on the Lazyroar main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments