Python Dictionary pop() Function
The Dictionary pop()
method removes an item with a specified key
from the dictionary and returns its value
.
This method is useful when you need to retrieve and remove a value from a dictionary in a single operation.
Syntax
my_dictionary.pop(key, default)
pop() Parameters
Python Dictionary pop()
method parameters:
Parameter | Condition | Description |
---|---|---|
key | Required | The key of the item to be removed and returned. |
default | Optional | The value to return if the key is not found in the dictionary. |
pop() Return Value
Python Dictionary pop()
function returns:
- the removed element from the dictionary, if
key
is found. - the value specified as default value (second argument), if
key
is not found.
If key
is not found and default
argument is not specified, a KeyError
exception is raised!
Examples
Example 1: Pop an element from the dictionary
The pop()
method is used to remove a key from the dictionary. Moreover, it returns the value
associated to the removed key
.
my_dict = {'name': 'Tom', 'age': 25}
removed_value = my_dict.pop('age')
print(my_dict) # Output {'name': 'Tom'}
print(removed_value) # Output: 25
output
{'name': 'Tom'}
25
Example 2: Pop an element not present from the dictionary but providing a default value
If key
is in the dictionary, the pop()
method removes it and returns its value
(no matter what you pass in as default
, since a pair key-value exists in the dictionary!).
my_dict = {'name': 'Tom', 'age': 25, 'job': 'Manager'}
removed = my_dict.pop('job', 'Developer') # pop with default value 'Developer'
print(my_dict) # Output: {'name': 'Tom', 'age': 25}
print(removed) # Output: Manager
output
{'name': 'Tom', 'age': 25}
Manager
But if key
is not in the dictionary, the method returns specified default
value.
my_dict = {'name': 'Tom', 'age': 25}
removed = my_dict.get('job','Developer') # pop with default value 'Developer'
print(my_dict) # Output: {'name': 'Tom', 'age': 25}
print(removed) # Output: Developer
output
{'name': 'Tom', 'age': 25}
Developer
Example 3: Pop an element not present from the dictionary without default value
If the key
to remove is not in the dictionary and default
value is not specified, then the pop()
method raises KeyError
exception.
my_dict = {'name': 'Tom', 'age': 25}
my_dict.pop('job') # raises KeyError: 'job'
output
Traceback (most recent call last):
File "main.py", line 2, in <module>
my_dict.pop('job')
KeyError: 'job'