w3resource

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


22. Insert an Element at the Beginning of an OrderedDict

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.

For more Practice: Solve these Related Problems:

  • Write a Python program to create an OrderedDict and insert a new key-value pair at the beginning using move_to_end() with last=False.
  • Write a Python program to add a key-value pair to the start of an OrderedDict by creating a new OrderedDict and updating it.
  • Write a Python program to implement a function that takes an OrderedDict and a new element, and returns a new OrderedDict with the element inserted at the beginning.
  • Write a Python program to demonstrate how to preserve order while inserting a new element at the start of an OrderedDict.

Go to:


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.

Python Code Editor:

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.