w3resource

Python: Insert an element at the beginning of a given OrderedDictionary

Python Collections: Exercise-22 with Solution

Write a Python program to insert an element at the beginning of a given Ordered Dictionary.

Sample Solution:

Python Code:

# Import the OrderedDict class from the collections module
from collections import OrderedDict

# Create an ordered dictionary 'color_orderdict' with key-value pairs
color_orderdict = OrderedDict([('color1', 'Red'), ('color2', 'Green'), ('color3', 'Blue')]) 

# Print a message to indicate the display of the original ordered dictionary
print("Original OrderedDict:")

# Print the content of 'color_orderdict'
print(color_orderdict)

# Insert an element at the beginning of the ordered dictionary
color_orderdict.update({'color4':'Orange'})

# Move the newly inserted element to the beginning of the ordered dictionary
color_orderdict.move_to_end('color4', last=False)

# Print a message to indicate the display of the updated ordered dictionary
print("\nUpdated OrderedDict:")

# Print the content of the updated 'color_orderdict'
print(color_orderdict) 

Sample Output:

Original OrderedDict:
OrderedDict([('color1', 'Red'), ('color2', 'Green'), ('color3', 'Blue')])
Insert an element at the beginning of the said OrderedDict:

Updated OrderedDict:
OrderedDict([('color4', 'Orange'), ('color1', 'Red'), ('color2', 'Green'), ('color3', 'Blue')])

Flowchart:

Flowchart - Python Collections: Insert an element at the beginning of a given OrderedDictionary.

Python Code Editor:

Previous: Write a Python program to count most and least common characters in a given string.
Next: Write a Python program to get the frequency of the tuples in a given list.

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.