Dictionary Methods
popitem()
Remove and return the last inserted (key, value) pair.
dict.popitem()
dict.popitem() removes and returns the last key-value pair added to the dictionary as a (key, value) tuple (LIFO - Last In, First Out order).
If the dictionary is empty, calling popitem() raises a KeyError.
Returns
A (key, value) tuple of the last inserted item.
Try it
Run it and change it
stack = {"a": 1, "b": 2, "c": 3}
last_key, last_val = stack.popitem()
print(f"Popped: {last_key}={last_val}")
print("Remaining:", stack)Worth knowing
- LIFO ordering: Since Python 3.7, dictionaries maintain insertion order, so
popitem()reliably removes the most recently added item.