Monday, November 18, 2024
Google search engine
HomeLanguagesHow to iterate over OrderedDict in Python?

How to iterate over OrderedDict in Python?

An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. 

Explanation: 

Input : original_dict = { ‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4 }

Output: a 1 b 2 c 3 d 4

Input: original_dict = {‘sayantan’:9, ‘sanjoy’:7, ‘suresh’:5, ‘rony’:2}

Output: sayantan 9 sanjoy 7 suresh 5 rony 2

Steps to perform iteration through Ordereddict in python : 

  • Import the ordereddict from collection in python.
  • Take the input of the ordereddict.
  • Iterate through the ordereddict in either of the two approaches given below:

Approach #1

Iterating through the ordereddict and printing the value.

Python3




# Python code to implement iteration
# over the ordereddict
 
# import required modules
from collections import OrderedDict
 
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
 
# iterating over the ordereddict
for key, value in od.items():
    print(key, value)


Output : 

a 1
b 2
c 3
d 4

Time Complexity: O(n)
Auxiliary Space: O(n)

The above code can also be written as – 

Python3




# Python code to implement iteration
# over the ordereddict
 
# import required modules
from collections import OrderedDict
 
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
 
# iterating over the ordereddict
for item in od.items():
    print(*item)


Output : 

a 1
b 2
c 3
d 4

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach #2

Iterating through the enumerate objects and printing the value. The enumerate() method is a method in which it adds a counter to the iterable object and returns the value in the form of an enumerate object. 

Python3




# Python code to implement iteration
# over the ordereddict
 
# import required modules
from collections import OrderedDict
 
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
 
# iterating through the enumerate objects
for i, (key, value) in enumerate(od.items()):
    print(key, value)


Output:

a 1
b 2
c 3
d 4

Time Complexity: O(n)
Auxiliary Space: O(n)

RELATED ARTICLES

Most Popular

Recent Comments