popitem() method removes and returns the last inserted key-value pair from a dictionary as a tuple. It modifies the original dictionary and is useful when you want to process or remove items one at a time.
Example: In this example, popitem() removes the last inserted key-value pair from the dictionary and returns it.
d = {1: "one", 2: "two", 3: "three"}
res = d.popitem()
print(res)
print(d)
Output
(3, 'three')
{1: 'one', 2: 'two'}
Explanation:
- d.popitem() removes the last inserted key-value pair (3, 'three').
- The returned tuple is stored in res, and the original dictionary is updated.
Syntax
dictionary.popitem()
- Parameter: None - does not accept any parameters.
- Return Value: Returns the removed (key, value) pair as a tuple and raises a KeyError if the dictionary is empty.
Examples
Example 1: In this example, the removed key-value pair is stored in a variable and then accessed separately.
d = {"A": 10, "B": 20, "C": 30}
item = d.popitem()
print(item)
print(item[0])
print(item[1])
Output
('C', 30)
C
30
Explanation:
- d.popitem() returns the tuple ('C', 30).
- item[0] gives the key, while item[1] gives the corresponding value.
Example 2: This example removes all key-value pairs one by one until the dictionary becomes empty.
d = {1: "A", 2: "B", 3: "C"}
while d:
print(d.popitem())
Output
(3, 'C') (2, 'B') (1, 'A')
Explanation:
- The while loop continues as long as the dictionary contains elements.
- Each call to d.popitem() removes and returns the last inserted key-value pair.
Example 3: This example shows what happens when popitem() is called on an empty dictionary.
d = {}
try:
d.popitem()
except KeyError:
print("Dictionary is empty.")
Output
Dictionary is empty.
Explanation:
- Calling d.popitem() on an empty dictionary raises a KeyError.
- The try-except block catches the exception and prevents the program from terminating.