Click for All Topics
KeyError
if the specified key is not present in the dictionary and no default value is given.pop()
method with a dictionary and pass a key as an argument, Python first calculates the hash value of the specified key and checks whether the specified index is pointing to the desired key-value pair in the hash table or not. If the key exists, Python removes the key-value pair from the hash table and returns the value associated with the removed key. If the key does not exist, a KeyError
is raised to indicate that the specified key is not present in the dictionary.Syntax –
dictionary.pop(key, default)
Parameters –
Example –
my_dict={'a':5,'b':10,'c':15,'d':20,'e':25}
print("Original Dictionary:\n",my_dict)
my_dict.pop('d')
print("Original dictionary after removing 'd':20 from dictionary:\n",my_dict)
# Output -
# Original Dictionary:
# {'a': 5, 'b': 10, 'c': 15, 'd': 20, 'e': 25}
# Original dictionary after removing 'd':20 from dictionary:
# {'a': 5, 'b': 10, 'c': 15, 'e': 25}
.pop()
method.Example –
student={'name':'anurag','year':4,'rollno':1234,'branch':'cse'}
print("Original Dictionary:",student)
return_value=student.pop('year')
print('Original Modified dictionary:",student)
print('year of the student:',return_value)
# Output -
# Original Dictionary: {'name': 'anurag', 'year': 4, 'rollno': 1234, 'branch': 'cse'}
# Original Modified dictionary: {'name': 'anurag', 'rollno': 1234, 'branch': 'cse'}
# year of the student: 4
Example – pop with the default value
course={1:'Data Science',2:'Full Stack',3:'Devops',4:'Cyber Security'}
print("Available Courses:\n",course)
return_course=course.pop(5,'course not found')
print("Modified Courses:\n",course)
print("return value:",return_course)
# Output -
# Available Courses:
# {1: 'Data Science', 2: 'Full Stack', 3: 'Devops', 4: 'Cyber Security'}
# Modified Courses:
# {1: 'Data Science', 2: 'Full Stack', 3: 'Devops', 4: 'Cyber Security'}
# return value: course not found
Example – pop without a default value and the item is not present
vacancy={'HR':1,'developer':3,'content writer':2,'data analyst':4}
print("Vacancy Available:\n",vacancy)
vacancy.pop('project manager')
# Output -
# Vacancy Available:
# {'HR': 1, 'developer': 3, 'content writer': 2, 'data analyst': 4}
# Traceback (most recent call last):
# File "/home/main.py", line 4, in
# vacancy.pop('project manager')
# KeyError: 'project manager'
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India