w3resource

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:

Python Collections: Sort the dictionary during the creation and print the members of the dictionary in reverse order.

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 Python skills with w3resource's quiz

Python: Tips of the Day

Memoization using LRU cache:

import functools

@functools.lru_cache(maxsize=128)
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)