w3resource

Python OrderedDict example: Adding items and printing contents


1. OrderedDict Creation

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.

For more Practice: Solve these Related Problems:

  • Write a Python program to create an OrderedDict from a list of tuples and then iterate over it to print each key-value pair.
  • Write a Python script to initialize an OrderedDict with several items, then print the keys in the order they were added.
  • Write a Python program to create an empty OrderedDict, add items using update(), and then display its content.
  • Write a Python function to create an OrderedDict from two lists (keys and values) and print the resulting dictionary.

Python Code Editor :

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.