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'
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
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}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.