Python OrderedDict Key-Value removal
6. Remove First Key-Value Pair
Write a Python program to create an OrderedDict with the following key-value pairs:
'Laptop': 40
'Desktop': 45
'Mobile': 35
'Charger': 25
Now remove the first key-value pair and print the updated OrderedDict.
Sample Solution:
Code:
from collections import OrderedDict
# Create an OrderedDict with the given key-value pairs
ordered_dict = OrderedDict([
('Laptop', 40),
('Desktop', 45),
('Mobile', 35),
('Charger', 25)
])
print("Original OrderedDict:")
print(ordered_dict)
# Remove the first key-value pair
print("\nRemove the first key-value pair of the said OrderedDict:")
ordered_dict.popitem(last=False)
# Print the updated OrderedDict
print("\nUpdated OrderedDict:")
print(ordered_dict)
Output:
Original OrderedDict: OrderedDict([('Laptop', 40), ('Desktop', 45), ('Mobile', 35), ('Charger', 25)]) Remove the first key-value pair of the said OrderedDict: Updated OrderedDict: OrderedDict([('Desktop', 45), ('Mobile', 35), ('Charger', 25)])
In the exercise above, the popitem(last=False) method of the OrderedDict is used to remove the first key-value pair (with the lowest index) from the dictionary. The last parameter is set to False to indicate that the item should be removed from the beginning of the dictionary.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to remove the first item from an OrderedDict using popitem(last=False) and then print the updated dictionary.
- Write a Python script to delete the first key-value pair from an OrderedDict and then iterate over the remaining items to display them.
- Write a Python function that accepts an OrderedDict, removes its first element, and returns both the removed pair and the new OrderedDict.
- Write a Python program to check if an OrderedDict is empty after removing its first element and then print an appropriate message.
Python Code Editor :
Previous: Python OrderedDict Key reordering.
Next: Python merging OrderedDicts with summed values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.