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:
d.popitem()
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': 'info@codingcreativo.it'
}
student.popitem()
print(student)
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': 'info@codingcreativo.it'
}
del_student = student.popitem()
print(del_student)
print(student)
In this case, the output generated is the following:
('mail', 'info@codingcreativo.it') {'name': 'Cristina', 'age': 20}
Python popitem – second example
This time we will try to delete from an empty dictionary.
student = {}
del_student = student.popitem()
print(del_student)
print(student)
An error message will be returned, noting that the dictionary is empty:
Traceback (most recent call last): File “/tmp/sessions/95c2c3a3544875f9/main.py”, 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.
Conclusion
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
How to find the maximum of N numbers