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
from collections import OrderedDict
od = OrderedDict({ 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 })
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
from collections import OrderedDict
od = OrderedDict({ 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 })
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
from collections import OrderedDict
od = OrderedDict({ 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 })
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)
Last Updated :
07 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...