Python: Sort the dictionary during the creation and print the members of the dictionary in reverse order
34. Create an Instance of an OrderedDict and Print in Reverse Order
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:
# Import the OrderedDict class from the collections module
from collections import OrderedDict
# Create a dictionary 'dict' with country names as keys and their international dialing codes as values
dict = {'Afghanistan': 93, 'Albania': 355, 'Algeria': 213, 'Andorra': 376, 'Angola': 244}
# Create a new OrderedDict 'new_dict' using the items of the original dictionary
new_dict = OrderedDict(dict.items())
# Loop through the keys in 'new_dict' and print each key and its corresponding value
for key in new_dict:
print(key, new_dict[key])
# Print a message to indicate the display of keys and values in reverse order
print("\nIn reverse order:")
# Loop through the keys in 'new_dict' in reverse order and print each key and its corresponding value
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:

For more Practice: Solve these Related Problems:
- Write a Python program to create an OrderedDict from a dictionary, sort it by keys, and then print the items in reverse order.
- Write a Python program to use collections.OrderedDict to store a dictionary and then iterate over it in reverse using reversed().
- Write a Python program to create an OrderedDict and then output its key-value pairs in descending order of keys.
- Write a Python program to implement a function that accepts a dictionary, sorts it, and returns an OrderedDict with items in reverse order.
Python Code Editor:
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.