w3resource

Python Data Structure: Sort the dictionary during the creation and print the members of the dictionary in reverse order

Python Data Structure: Exercise-9 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:

Flowchart: Sort the dictionary during the creation and  print the members of the dictionary in reverse order

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to get the unique enumeration values.
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.



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://w3resource.com/python-exercises/data-structures-and-algorithms/python-data-structure-exercise-9.php