Home »
Python
Python Dictionary pop() Method with Example
Python Dictionary pop() Method: Here, we are going to learn how to remove an item with specified key from the dictionary?
Submitted by IncludeHelp, on November 26, 2019
Dictionary pop() Method
pop() method is used to remove an item from the dictionary with specified key from the dictionary.
Syntax:
dictionary_name.pop(key, value)
Parameter(s):
- key – It represents the specified key whose value to be removed.
- value – It is an optional parameter, it is used to specify the value to be returned if “key” does not exist in the dictionary.
Return value:
The return type of this method is the type of the value, it returns the value which is being removed.
Note: If we do not specify the value and key does not exist in the dictionary, then method returns an error.
Example 1:
# Python Dictionary pop() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# removing 'roll_no'
x = student.pop('roll_no')
print(x, ' is removed.')
# removing 'name'
x = student.pop('name')
print(x, ' is removed.')
# removing 'course'
x = student.pop('course')
print(x, ' is removed.')
# removing 'perc'
x = student.pop('perc')
print(x, ' is removed.')
# printing default value if key does
# not exist
x = student.pop('address', 'address does not exist.')
print(x)
Output
data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
101 is removed.
Shivang is removed.
B.Tech is removed.
98.5 is removed.
address does not exist.
Demonstrate the example, if key does not exist and value is not specified.
Example 2:
# Python Dictionary pop() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# demonstrating, when method returns an error
# if key does not exist and value is not specified
student.pop('address')
Output
data of student dictionary...
{'course': 'B.Tech', 'name': 'Shivang', 'roll_no': 101, 'perc': 98.5}
Traceback (most recent call last):
File "main.py", line 17, in <module>
student.pop('address')
KeyError: 'address'
TOP Interview Coding Problems/Challenges