Python Dictionary - popitem() Method
The Python popitem() method is used to delete a last key-value pair of the dictionary. Elements in a dictionary are unordered and hence it is not possible to find last element of a dictionary and consequently deletes random key-value pair.
Syntax
dictionary.popitem()
Parameters
No parameter is required.
Return Value
Returns the deleted key-value pair of the dictionary.
Example: popitem() method of dictionary
In the example below, popitem() method is used to delete last key-value pair of the dictionary. As dictionary is an unordered data container therefore deletes random key-value pair. Deleted key-value pair can be accessed through method object as tuple.
Info = { 'name': 'John', 'age': 25, 'city': 'London' } method_object = Info.popitem() print(method_object) print(Info)
The output of the above code will be:
('name', 'John') {'age': 25, 'city': 'London'}
Example: popitem() method on empty dictionary
If popitem() method is used on empty dictionary, it will raise an exception.
Info = {} Info.popitem() print(Info)
The output of the above code will be:
Traceback (most recent call last): File "Main.py", line 2, in <module> Info.popitem() KeyError: 'popitem(): dictionary is empty'
❮ Python Dictionary Methods