pop(), takes one argument ( key as input ) .
Returns : the value of the input key.
The original dictionary is changed after removal of key value pair.
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.pop('b')
print(x)
print(my_dict)
Output is here
Two
{'a': 'One', 'c': 'Three'}
If input key is not available then keyerror will be generated.
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.pop('d')
print(x)
print(my_dict)
Output ( error as input key is not available )
KeyError: 'd'
Providing default value if key is not available
pop() can return a default value if the key doesn't exist, avoiding KeyError.
my_dict = {'a': 'One', 'b': 'Two', 'c': 'Three'}
value = my_dict.pop('d', 'Key Not Found') # No error
print(value) # Output: Key Not Found
pop() can be used in a loop to safely remove elements.
my_dict = {'a': 1, 'b': 2, 'c': 3}
while my_dict:
key, value = my_dict.popitem()
print(f"Removed {key}: {value}")
Output
Removed c: 3
Removed b: 2
Removed a: 1
Pop Multiple Items Safely Using a Loop
my_dict = {'x': 10, 'y': 20, 'z': 30}
keys_to_remove = ['x', 'y', 'a'] # 'a' doesn't exist
for key in keys_to_remove:
value = my_dict.pop(key, 'Key not found')
print(f"Key: {key}, Value: {value}")
print(my_dict)
Output
Key: x, Value: 10
Key: y, Value: 20
Key: a, Value: Key not found
{'z': 30}
« All dictionary methods
← Subscribe to our YouTube Channel here