The pop()
method in Python is a dictionary method that removes and returns an item with the specified key from a dictionary. If the key is not found, it can also return a default value specified as the second argument. If the specified key is not found and no default value is provided, a KeyError exception is raised.
Parameter Values
Parameter | Description |
---|---|
key | The key to be removed and returned from the dictionary. |
default | The value to be returned if the key is not found in the dictionary. If not specified, a KeyError is raised. |
Return Values
The pop()
method returns a value of any type present in the dictionary.
How to Use pop()
in Python
The pop()
method removes and returns an element from a dictionary based on the specified key.
my_dict = {'a': 1, 'b': 2, 'c': 3}
popped_value = my_dict.pop('b')
print('Popped value:', popped_value)
print('Updated dictionary:', my_dict)
If the key does not exist in the dictionary, pop()
will raise a KeyError.
my_dict = {'a': 1, 'b': 2, 'c': 3}
popped_value = my_dict.pop('z')
print('Popped value:', popped_value)
print('Updated dictionary:', my_dict)
You can provide a default value to return if the key is not found by using the second argument in pop()
.
my_dict = {'a': 1, 'b': 2, 'c': 3}
popped_value = my_dict.pop('z', 'Key not found')
print('Popped value:', popped_value)
print('Original dictionary:', my_dict)