Press ESC to close

Python popitem

0 355

In Python, the popitem method, on dictionaries, removes the last key: value pair entered in the dictionary. Furthermore, this method adds the deleted pair as a tuple.

This method has no parameters, so its syntax is simply this:


If the dictionary has no elements the method returns a keyError.

Python popitem – first example

In this first example we delete the last element from our student dictionary.

Here is a possible implementation of the proposed algorithm:

student = {
'name': 'Cristina', 'age': 20, 'mail': ''

In output we will see this result:

{'name': 'Cristina', 'age': 20}

Try the above code in the online compiler which you will find at the following link: online Python compiler.

Now we also print the deleted element always using the Python popitem method on the dictionaries:

student = {
'name': 'Cristina', 'age': 20, 'mail': ''
del_student = student.popitem()

In this case, the output generated is the following:

('mail', '')
{'name': 'Cristina', 'age': 20}

Python popitem – second example

This time we will try to delete from an empty dictionary.

student = {}
del_student = student.popitem()

An error message will be returned, noting that the dictionary is empty:

Traceback (most recent call last): File “/tmp/sessions/95c2c3a3544875f9/”, line 2, in <module> del_student = student.popitem() KeyError: ‘popitem(): dictionary is empty’

It is very important to know how to read errors, so experiment every time you are faced with a new topic.


In this lesson we talked about the popitem method on dictionaries in Python, later we will see how to put these methods into practice.

Some useful links

Python tutorial

Python Compiler

Install Python


Assignment operators

How to find the maximum of N numbers


Bubble sort

Matplotlib Plot

Other stories

for loop Python

Next Story

Python dictionary pop

Previous Story