Python OrderedDict Reversal

Python OrderedDict Data Type: Exercise-4 with Solution

Write a Python program that reverses the order of a given OrderedDict.

Sample Solution:


from collections import OrderedDict

# Create an OrderedDict
ordered_dict = OrderedDict()
ordered_dict['Laptop'] = 40
ordered_dict['Desktop'] = 45
ordered_dict['Mobile'] = 35
ordered_dict['Charger'] = 25

# Reverse the order of the OrderedDict
reversed_dict = OrderedDict(reversed(list(ordered_dict.items())))

# Print the reversed OrderedDict
print("Original OrderedDict:")

print("\nReversed OrderedDict:")


Original OrderedDict:
OrderedDict([('Laptop', 40), ('Desktop', 45), ('Mobile', 35), ('Charger', 25)])

Reversed OrderedDict:
OrderedDict([('Charger', 25), ('Mobile', 35), ('Desktop', 45), ('Laptop', 40)])

In the exercise above, we use the reversed() function to reverse the order of items in the OrderedDict. Then, we create a new OrderedDict using the reversed list of items.


Flowchart: Python OrderedDict Reversal.

Previous: Python OrderedDict access and existence check.
Next: Python OrderedDict Key reordering.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.