Skip to main content

Python Dictionary popitem() Function

The Dictionary popitem() method removes and returns the last inserted key-value pair from the dictionary.

note

Pairs are returned in Last-In First-Out (LIFO) order.

Syntax

my_dictionary.popitem()

popitem() Parameters

Python Dictionary popitem() function does not take any parameters.

popitem() Return Value

Python Dictionary popitem() function removes and returns the (key, value) pair from the dictionary according to the LIFO (Last-In First-Out) order. In particular:

  • Return the latest inserted element (key,value) pair from the dictionary.
  • Remove the returned element pair from the dictionary.
danger

Before Python 3.7, the popitem() method would return and remove a random element (key, value) pair from the dictionary.

Examples

Example 1: Basic Usage of popitem() method of dictionaries

For example, let's remove the last inserted uten from the dictionary:

my_dict = {'name': 'Tom', 'age': 25}
removed = my_dict.popitem()

print(my_dict) # Output: {'name': 'Tom'}
print(removed) # Output: ('age', 25)

output:

{'name': 'Tom'}
('age', 25)

Another example: let's add a new element pair in a dictionary and then use the popitem() method to remove it:

my_dict = {'name': 'Tom', 'age': 25}

print(my_dict) # Output: {'name': 'Tom', 'age': 25}

# inserting a new element pair
my_dict['job'] = 'Developer'

# my_dict after insertion
print(my_dict) # Output: {'name': 'Tom', 'age': 25, 'job': 'Developer'}

removed = my_dict.popitem() # remove last inserted (LIFO policy)

print(my_dict) # Output: {'name': 'Tom', 'age': 25}
print(removed) # Output: ('job', 'Developer')

output:

{'name': 'Tom', 'age': 25, 'job': 'Developer'}
{'name': 'Tom', 'age': 25}
('job', 'Developer')

Example 2: popitem() on an Empty Dictionary

Using popitem() method on an empty dictionary, raises a KeyError exception.

my_dict = {}
removed = my_dict.popitem() # raises KeyError exception

print(removed)

output:

Traceback (most recent call last):
File "main.py", line 2, in <module>
removed = my_dict.popitem()
KeyError: 'popitem(): dictionary is empty'

To avoid KeyError exception when using popitem() method, you must check if the dictionary is empty before calling the popitem() method.

my_dict = {}
if my_dict: # check if dictionary is NOT empty
removed = my_dict.popitem()
print(removed)
else:
print('Dictionary is empty!')

output:

Dictionary is empty!