The Dictionary pop() method removes an item with a specified key from the dictionary and returns its value.
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() method returns:
- the removed element from the dictionary, if
keyis found. - the value specified as default value (second argument), if
keyis not found.
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: 25output
{'name': 'Tom'}
25Example 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: Manageroutput
{'name': 'Tom', 'age': 25}
ManagerBut 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: Developeroutput
{'name': 'Tom', 'age': 25}
DeveloperExample 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'