What does the popitem() method do in Python dictionaries?
a) Removes and returns the last inserted key-value pair from the dictionary
b) Removes and returns the first key-value pair from the dictionary
c) Removes all key-value pairs from the dictionary
d) Adds a new key-value pair to the dictionary
Answer:
a) Removes and returns the last inserted key-value pair from the dictionary
Explanation:
The popitem()
method in Python dictionaries removes and returns the last inserted key-value pair as a tuple. This method is useful when you need to remove and process elements from a dictionary in the order they were added, especially in Python 3.7 and later, where dictionaries maintain insertion order.
# Example of popitem() method
student = {"name": "John", "age": 20, "major": "Computer Science"}
last_item = student.popitem()
print(last_item) # Output: ('major', 'Computer Science')
print(student) # Output: {'name': 'John', 'age': 20}
In this example, the popitem()
method removes and returns the last inserted key-value pair (“major”: “Computer Science”) from the student
dictionary.
The popitem()
method is particularly useful in scenarios where you need to process or remove items from a dictionary in the reverse order of their insertion.