Python Dictionary pop() Method

value = my_dict.pop(key, default) removes a specified key and returns its value. Without a default, a missing key raises KeyError; with a default, that value is returned instead.

See the complete Dictionary Methods table for the other dictionary operations in this cluster.

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



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer