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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-ordereddict-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics