Python 3 reference · Dictionary Methods
Python Dictionary popitem() Method
Remove and return the last inserted (key, value) pair (LIFO order). Raises KeyError if the dict is empty.
Python 3 Since 3.0
Syntax
dict.popitem()
Return value
A (key, value) tuple.
Examples
d = {"a": 1, "b": 2, "c": 3}
print(d.popitem(), d)
Output
('c', 3) {'a': 1, 'b': 2}tasks = {"t1": "write", "t2": "test"}
while tasks:
key, task = tasks.popitem()
print(key, task)
Output
t2 test t1 write
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.7 | Guaranteed to remove the last inserted item (LIFO). |
Related
dict.pop()· Remove a key and return its value. Returns the default if given and the key is missing; otherwise raises KeyError.dict.clear()· Remove every key and value from the dictionary in place, leaving it empty. Other references see the change too.- Python Dictionaries · tutorial