Python OrderedDict Reversal
Write a Python program that reverses the order of a given OrderedDict.
Sample Solution:
Code:
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(ordered_dict)
print("\nReversed OrderedDict:")
print(reversed_dict)
Output:
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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics