Python Dictionary | pop method
Start your free 7-days trial now!
Python's dict.pop(~) method removes the key/value pair at the given key from a dictionary and then returns the removed value.
Parameters
1. key | any type
The key of the key/value pair to be removed from the dictionary.
2. default | any type | optional
The default value to return if the specified key is not present in the dictionary.
Return value
Case | Return value |
|---|---|
| value corresponding to |
|
|
|
|
Examples
Basic usage
To remove the key/value pair for "Emma" and return its corresponding value:
test_scores = {"Mike": 3, "Adam": 5,"Emma": 7}print("Emma's score was ", test_scores.pop("Emma"))print("The remaining dictionary is ", test_scores)
Emma's score was 7The remaining dictionary is {'Mike': 3, 'Adam': 5}
We remove the key "Emma" from test_scores dictionary and then return the corresponding value of 7.
Default parameter
To remove the key/value pair for "Kate" and return the value:
test_scores = {"Mike": 3, "Adam": 5,"Emma": 7}print("Kate's score was ", test_scores.pop("Kate", "N/A"))
Kate's score was N/A
The default argument "N/A" is returned as "Kate" was not found in dictionary test_scores.
KeyError
If we do not provide a default argument, and the key does not exist in the dictionary, KeyError is raised:
test_scores = {"Mike": 3, "Adam": 5,"Emma": 7}print("Kate's score was ", test_scores.pop("Kate"))
KeyError: 'Kate'