pop(): removes a specified key from a dictionary and returns the corresponding value

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
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



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-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer