Write a Python Program to Delete an Element From a Dictionary

Deleting an element from a dictionary in Python is a common operation.

In Python, dictionaries are one of the built-in data types that allow you to store key-value pairs.

In this tutorial, we will discuss how to remove an element from a dictionary using Python.


First, let us define a dictionary to work with:

sample_dict = {'apple': 2, 'banana': 3, 'orange': 4, 'grape': 5}

To delete an element from this dictionary, we will use the del keyword followed by the key of the element we want to delete:

del sample_dict['apple']

After running the above line of code, the dictionary sample_dict will no longer contain the key-value pair associated with the key ‘apple’.

We can also use the pop() method to delete an element from the dictionary.

This method takes a key as an argument and removes the corresponding key-value pair from the dictionary.

Additionally, the method returns the value associated with the key that was removed.

removed_value = sample_dict.pop('banana')

In this case, the key-value pair associated with the key ‘banana’ will be removed from sample_dict, and the value 3 will be assigned to removed_value.

If we try to delete a key that does not exist in the dictionary, we will get a KeyError exception.

To avoid this, we can use the get() method to return a default value if the key does not exist.

removed_value = sample_dict.pop('pear', None)

In this case, if the key ‘pear’ does not exist in sample_dict, None will be assigned to removed_value.


In conclusion, we can delete an element from a dictionary in Python using the del keyword or the pop() method.

It is important to handle cases where the key we want to delete does not exist in the dictionary by using the get() method to avoid exceptions.