Python Dictionary pop() Method
The pop()
method removes and returns the value of a specified key from a dictionary.
Syntax
dictionary.pop(key, default)
Parameters
key
: The key of the item to remove from the dictionary.
default
(Optional): The value to return if the key is not found in the dictionary. If not provided, and the key is not found, a KeyError
is raised.
Return value
The value associated with the specified key.
If the key is not found, and the default
is provided, it returns the default
value.
If the key is not found, and the default
is not provided, a KeyError
is raised.
Example 1: Basic Usage
person = {"name": "James", "age": 35, "city": "New York"}
removed_item = person.pop("city")
print(removed_item) # Output: New York
print(person) # Output: {'name': 'James', 'age': 35}
Example 2: Using Default Value
person = {"name": "James", "age": 35}
removed_item = person.pop("city", "Not found")
print(removed_item) # Output: Not found
print(person) # Output: {'name': 'James', 'age': 35}
Example 3: Missing key without default value
person = {"name": "James", "age": 35}
removed_item = person.pop("city") # Raises KeyError
Example 4: Handling KeyError
You can handle KeyError
using try-except
block.
person = {"name": "James", "age": 35}
try:
removed_item = person.pop("city")
print(removed_item)
except KeyError:
print("Key not found!")
Output:
Key not found!