Home >>Python Dictionary Methods >Python Dictionary popitem() Method

Python Dictionary popitem() Method

Python Dictionary popitem() Method

Python Dictionary popitem() Method in python dictionary generally, is used to removes an arbitrary element that was last inserted into the dictionary and return its value. It returns an error, if the dictionary is empty.

Syntax:
dictionary.popitem()
Here is an example of Python Dictionary popitem() Method:

person = {
"name": "raj",
"lname": "singh",
"year": 1980
}
person.popitem()
print(person)

Output:
{'name': 'raj', 'lname': 'singh'}
Example 2:

invent = {}  
print(invent)  
x = invent.popitem()  
print("Removed",x)  
print(invent)

Output:
KeyError: 'popitem(): dictionary is empty'