How to delete a key from a Python dictionary


Estimated reading time: 2 minutes

This is an addition to the list of questions you may get when in an interview and you are asked to give an overview of Python.

As with how to create an empty dictionary in Python, how to add values to a python dictionary, and how to sort a python dictionary we will take you through the steps here of how to delete a key from a python dictionary.

How to delete a key from a Python dictionary.

How to use the pop() method to delete a key from a dictionary

In the below example we tell Python to find the key “Key1”, then when it does it prints the python dictionary without that key or its value.

empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
print(empty_dict1)

#1. Use the pop function
empty_dict1.pop('Key1')
print(empty_dict1)

Result:
{'Key2': '2', 'Key3': '3'}

How to use the Del keyword to delete a key from a dictionary

In this example, we are taking the output of the above example, and just telling the logic to remove the key “Key2” then what it does is it prints the python dictionary without that key or its value.

del empty_dict1["Key2"]
print(empty_dict1)

Result:
{'Key3': '3'}

How to use dict.clear() to delete a key from a dictionary

In this final example, we use dict.clear(). Note this will empty everything out of the dictionary, so be careful in its use.

As can be seen, it takes the output of the previous example and empties it completely.

empty_dict1.clear() # Removes everything from the dictionary.
print(empty_dict1)

Result:
{}

Leave a Reply

Your email address will not be published. Required fields are marked *