Python dictionary pop

In Python, the pop method on the dictionary, allows you to remove an element from the dictionary in question.

The method accepts two parameters, one mandatory, the other optional. The syntax is, therefore, the following:

d.pop(keydef)

Where key removes all the key: value pair from the dictionary d. This parameter is mandatory. This means that I cannot write d.pop(), it would result in an error (keyError).

While def represents the default value to return if the key does not exist, this way you can avoid the (keyError). This parameter, on the other hand, is optional.

Python dictionary pop – first example

In this first example, taking the student dictionary into consideration, let’s try to delete a key: value pair.

So here’s a code example:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
student.pop('age')
print(student)

Try it in the online Python compiler that you will find at the following link: online compiler.

The displayed output will be the following:

{‘name’: ‘Cristina’, ‘mail’: ‘info@codingcreativo.it’}
We also try to print the deleted item.


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
del_element = student.pop('age')
print(del_element)
print(student)

Thus we are able to print the deleted element, as well as the dictionary with the missing element.

Python dictionary pop – second example

In this second example, we take the same dictionary as the previous example as a reference but, this time, we try to delete a key that does not exist.

Here, then, is a possible example:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
student.pop('surname')
print(student)

In this case there is an error like:

Traceback (most recent call last): File “/tmp/sessions/7ad116a7a00a02b7/main.py”, line 4, in student.pop (‘surname’) KeyError: ‘surname’

This is a KeyError, this clearly indicates that there is an error in the surname key.

If instead we specify the optional def parameter, the error will not be returned, but what is specified in def.

So here’s an example:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
del_element = student.pop('surname','non presente')
print(del_element)
print(student)

The output displayed is this:

non presente
{'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'}

Conclusion

In this lesson, on Python, we studied the pop method on the dictionary, creating two simple practical examples in order to understand how it works.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *