Skip to content

Python Dictionary popitem() Method

How to use Python's dictionary popitem() method to remove and return the last inserted key-value pair in LIFO (Last-In First-Out) order, including handling empty dictionaries and exceptions.

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

Syntax

my_dictionary.popitem()

popitem() Parameters

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

popitem() Return Value

Python Dictionary popitem() method 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.

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}

my_dict['job'] = 'Developer'

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!
Navigation