Python: Sort the dictionary during the creation and print the members of the dictionary in reverse order
Python Collections: Exercise-34 with Solution
Write a Python program to create an instance of an OrderedDict using a given dictionary. Sort the dictionary during the creation and print the members of the dictionary in reverse order.
Sample Solution:
Python Code:
from collections import OrderedDict
dict = {'Afghanistan': 93, 'Albania': 355, 'Algeria': 213, 'Andorra': 376, 'Angola': 244}
new_dict = OrderedDict(dict.items())
for key in new_dict:
print (key, new_dict[key])
print("\nIn reverse order:")
for key in reversed(new_dict):
print (key, new_dict[key])
Sample Output:
Afghanistan 93 Albania 355 Algeria 213 Andorra 376 Angola 244 In reverse order: Angola 244 Andorra 376 Algeria 213 Albania 355 Afghanistan 93
Flowchart:

Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to count the number of students of individual class.
Next: Write a Python program to group a sequence of key-value pairs into a dictionary of lists.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Use Reversed() In for Loops:
>>> tasks = ['laundry', 'picking up kids', 'gardening', 'cooking'] >>> for task in reversed(tasks): ... print(task) ... cooking gardening picking up kids laundry
- Exercises: Weekly Top 12 Most Popular Topics
- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion