Python OrderedDict example: Adding items and printing contents

Python OrderedDict Data Type: Exercise-1 with Solution

Write a Python program that creates an OrderedDict and adds some items. Print the OrderedDict contents.

Sample Solution:


from collections import OrderedDict

# Create an OrderedDict
ordered_dict = OrderedDict()

# Add items
ordered_dict['Laptop'] = 15
ordered_dict['Desktop'] = 40
ordered_dict['Mobile'] = 50

# Print the OrderedDict contents
for item, quantity in ordered_dict.items():
    print(f"Itemt: {item}, Quantity: {quantity}")


Itemt: Laptop, Quantity: 15
Itemt: Desktop, Quantity: 40
Itemt: Mobile, Quantity: 50

In the exercise above, we create an OrderedDict called "ordered_dict" and add some key-value pairs to it. Upon iterating through the OrderedDict, the items are printed in the same order as they were entered.


Flowchart: Python OrderedDict example: Adding items and printing contents.

Previous: Python Extended Data Type OrderedDict Exercises Home.
Next: Python OrderedDict sorting: Keys and values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.