w3resource

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:

Code:

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}")

Output:

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:

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.



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://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-index-ordereddict-exercise-1.php