Python Dictionary pop() Method
The Python pop() method removes and returns the value of a specified key from a dictionary. If the key isn't found, you can provide a default value to return instead of raising an error. Example:
d = {'a': 1, 'b': 2, 'c': 3}
v = d.pop('b')
print(v)
v = d.pop('d', 'Not Found')
print(v)
Output
2 Not Found
Explanation:
- pop('b') removes key 'b' and returns 2, the dictionary becomes {'a': 1, 'c': 3}.
- pop('d', 'Not Found') returns 'Not Found' since 'd' doesn’t exist.
Syntax of Pop()
dict.pop(key, default)
Parameters:
- key: The key to be removed from the dictionary.
- default: (Optional) The value to return if the key isn't found. If not provided, a KeyError is raised if the key is missing.
Returns:
- If the key is found: It removes the key-value pair from the dictionary and returns the value associated with the key.
- If the key is not found: Returns the default value if provided, or raises a KeyError if no default value is provided.
Examples of pop()
Example 1: In this example, we remove the key from the dictionary using pop(). Since the key exists, it will be removed and its value will be returned.
d = {'name': 'Alice', 'age': 25}
val = d.pop('age')
print(val)
print(d)
Output
25 {'name': 'Alice'}
Explanation:
- pop('age') removes key 'age' and returns 25, the dictionary becomes {'name': 'Alice'} and print(d) shows the updated dictionary.
Example 2: In this example, we try to remove the key 'country' from the dictionary using pop(). Since the key does not exist and no default value is provided, Python will raise a KeyError.
d = {'city': 'Delhi'}
val = d.pop('country')
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 2, in <module>
val = d.pop('country')
KeyError: 'country'
Explanation: pop('country') tries to remove key 'country', but it doesn't exist in the dictionary, so it raises a KeyError.
Example 3: In this example, we repeatedly remove the first key-value pair from the dictionary using pop(). We use a while loop that continues until the dictionary is empty.
d = {'a': 1, 'b': 2, 'c': 3}
while d:
key = list(d.keys())[0]
val = d.pop(key)
print(f"Removed {key}: {val}")
Output
Removed a: 1 Removed b: 2 Removed c: 3
Explanation: while loop repeatedly removes and prints the first key-value pair from the dictionary using pop() until the dictionary is empty.
Also Read:
- Python Dictionary Methods
- Python | Ways to remove a key from dictionary
- Python Dictionary popitem() method
- Python - Remove last element from dictionary