A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-dictionary-pop-method/ below:

Python Dictionary pop() Method - GeeksforGeeks

Python Dictionary pop() Method

Last Updated : 11 Jul, 2025

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:

Python
d = {'a': 1, 'b': 2, 'c': 3}
v = d.pop('b')
print(v)  

v = d.pop('d', 'Not Found')
print(v) 

Explanation:

Syntax of Pop()

dict.pop(key, default)

Parameters:

Returns:

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.

Python
d = {'name': 'Alice', 'age': 25}
val = d.pop('age')

print(val)      
print(d)

Output
25
{'name': 'Alice'}

Explanation:

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.

Python
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.

Python
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:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4