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)
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
07 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...