Python dictionary Method - pop()
The pop()
method is a built-in dictionary method in Python that removes and returns the value for a given key in the dictionary. The syntax for the pop()
method is:
value = my_dict.pop(key[, default])oSurce:www.theitroad.com
Here, my_dict
is the dictionary to remove the key-value pair from, key
is the key to remove, and default
is an optional value to return if the key is not found in the dictionary.
If the key is found in the dictionary, the corresponding value is returned and the key-value pair is removed from the dictionary. If the key is not found in the dictionary and a default
value is provided, the default
value is returned. If the key is not found in the dictionary and no default
value is provided, a KeyError
is raised.
Here's an example:
# create a dictionary my_dict = {'apple': 3, 'banana': 2, 'cherry': 5} # remove the 'banana' key-value pair value = my_dict.pop('banana') # print the value and the updated dictionary print(value) print(my_dict)
Output:
2 {'apple': 3, 'cherry': 5}
In this example, we create a dictionary my_dict
with three key-value pairs. We then use the pop()
method to remove the 'banana'
key-value pair from the dictionary. The value 2
is returned and stored in the variable value
. We then print the value and the updated dictionary.
If we try to remove a key that doesn't exist in the dictionary, a KeyError
is raised:
# create a dictionary my_dict = {'apple': 3, 'banana': 2, 'cherry': 5} # try to remove a key that doesn't exist value = my_dict.pop('orange')
Output:
KeyError: 'orange'
To avoid a KeyError
, we can provide a default value to return if the key is not found:
# create a dictionary my_dict = {'apple': 3, 'banana': 2, 'cherry': 5} # try to remove a key that doesn't exist and provide a default value value = my_dict.pop('orange', 0) # print the value and the updated dictionary print(value) print(my_dict)
Output:
0 {'apple': 3, 'banana': 2, 'cherry': 5}
In this example, we try to remove the 'orange'
key-value pair from the dictionary, but since the key doesn't exist, we provide a default value of 0
. The value 0
is returned and stored in the variable value
. We then print the value and the updated dictionary.