w3resource

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-index-ordereddict-exercise-4.php