The pop method
The pop method removes an element from a dictionary by its key and returns its value. In the first parameter of the method, we set the element key, in the second optional parameter - the default value.
Syntax
dictionary.pop(key, [default value])
Example
Let's find an element by key and remove it using the pop method:
dct = {
'a': 1,
'b': 2,
'c': 3
}
print(dct.pop('a', '!'))
print(dct)
Result of code execution:
1
{'b': 2, 'c': 3}
Example
Now let's try to find and delete an element by a key that is not in the dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
print(dct.pop('e', '!'))
print(dct)
Result of code execution:
!
{'a': 1, 'b': 2, 'c': 3}
Example
Let's modify the previous example so that there is no default value for a non-existent key:
dct = {
'a': 1,
'b': 2,
'c': 3
}
print(dct.pop('e'))
print(dct)
After executing the code, the method will return us an error:
KeyError: 'e'
See also
-
method
popitem,
which deletes a key-value pair -
method
clear,
which deletes all elements of the dictionary -
method
setdefault,
which adds a value for the default key -
function
len,
which returns the length of the dictionary