Tutorial Study Image

Python popitem()

The popitem() function in python removes the last inserted element pair(key, value) from the dictionary. And the removed element is returned as the output. Hence we can say that this method uses Last In First Out (LIFO) strategy.


dict.popitem()
 

popitem() Parameters:

The popitem() method doesn't take any parameters. This method is used in set algorithms and it is the best way to destructively iterate through the dictionary,

 

popitem() Return Value

If the dictionary is empty the popitem() method raises a KeyError.

Input Return Value
dictionary last inserted element(tuple)

Examples of popitem() method in Python

Example 1: How popitem() works in Python?


persondet = {'name': 'Jhon', 'age': 35, 'salary': 5000.0}

# ('salary', 5000.0) is inserted at the last, so it is removed.
output= persondet.popitem()

print('Output Value = ', output)
print('Personal Details = ', persondet)

# inserting a new element pair
persondet['job'] = 'Electritian'

# now ('job', 'Electritian') is the latest element
output = persondet.popitem()

print('Output Value = ', output)
print('Personal Details = ', persondet)
 

Output:


Output Value =  ('salary', 5000.0)
Personal Details =  {'name': 'Jhon', 'age': 35}
Output Value =  ('job', 'Electritian')
Personal Details =  {'name': 'Jhon', 'age': 35}

Example 2: popitem() raises KeyError with empty dictionary


persondet = {}  
# Displaying result  
print(persondet)  
per = persondet.popitem()  
print("Removed",per)  
print(persondet)  
 

Output:


KeyError: 'popitem(): dictionary is empty'