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:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating over the ordereddictfor key, value in od.items(): print(key, value) |
Output :
a 1 b 2 c 3 d 4
The above code can also be written as –
Python3
# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating over the ordereddictfor item in od.items(): print(*item) |
Output :
a 1 b 2 c 3 d 4
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 modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating through the enumerate objectsfor i, (key, value) in enumerate(od.items()): print(key, value) |
Output:
a 1 b 2 c 3 d 4


