w3resource

Python OrderedDict exercises with solutions


Python OrderedDict Data Type [ 10 exercises with solution ]


[An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor]

Python OrderedDict is a dict subclass that remembers the order in which its items were inserted. When we iterate over an OrderedDict, the items will be returned in the order they were inserted, not in some arbitrary order.

The main features of OrderedDict are:

  • Unlike regular dictionaries, an OrderedDict remembers the order in which items were inserted.
  • When iterating through an OrderedDict, the items are returned in the order they were inserted.

1. Write a Python program that creates an OrderedDict and adds some items. Print the OrderedDict contents.
Click me to see the sample solution

2. Write a Python program that sorts the OrderedDict by its keys. Sort the OrderedDict by its values as well.
Click me to see the sample solution

3. Write a Python program that accesses an item in the OrderedDict by its key. Check if a specified item exists in the OrderedDict as well.
Click me to see the sample solution

4. Write a Python program that reverses the order of a given OrderedDict.
Click me to see the sample solution

5. Write a Python program to create an OrderedDict with the following key-value pairs:
'Laptop': 40
'Desktop': 45
'Mobile': 35
'Charger': 25
Now move the 'Desktop' key to the end of the dictionary and print the updated contents.
Click me to see the sample solution

6. Write a Python program to create an OrderedDict with the following key-value pairs:
'Laptop': 40
'Desktop': 45
'Mobile': 35
'Charger': 25
Now remove the first key-value pair and print the updated OrderedDict.
Click me to see the sample solution

7. Write a Python function that merges two OrderedDict objects. If there are duplicate keys, sum their values. Print the merged OrderedDict.
Click me to see the sample solution

8. Write a Python function that creates an OrderedDict and removes a key-value pair from the OrderedDict using a given key.
Click me to see the sample solution

9. Write a Python program that creates an OrderedDict and populates it with random integer values as values and their ASCII characters as keys. Print the OrderedDict.
Click me to see the sample solution

10. Write a Python function that takes a list of words and returns an OrderedDict where keys are the words and values are the lengths of the words.
Click me to see the sample solution

Python Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.