Python Program to Delete an Element From a Dictionary

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using del keyword

my_dict = {31: 'a', 21: 'b', 14: 'c'}

del my_dict[31]

print(my_dict)

Output

{21: 'b', 14: 'c'}

In the code above, the key:value pair with key as 31 is deleted using del keyword. del keyword gives a KeyError if the key is not present in the dictionary.


Example 2: Using pop()

my_dict = {31: 'a', 21: 'b', 14: 'c'}

print(my_dict.pop(31))

print(my_dict)

Output

a
{21: 'b', 14: 'c'}

Pass the key 31 as an argument to the pop() method. It deletes the key:value pair with key as 31 as shown in the output.

pop() also returns the value of the key passed.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges