A dictionary has always been an important and powerful collection of data for programming language users in general and Python programming language users in particular. Because it helps the process of manipulating the database faster. You can add and remove keys. So, today I will guide you who are looking to learn how to Delete key from dictionary python with the most efficient method to do it.
What is a dictionary in Python?
A dictionary is a collection of unsorted objects. Key-value pairs are use to identify items. Therefore, the keys correspond to the entries in the list. When we need to query an item, we may do so by using its key in Python.
>>> # Declare a dictionary >>> my_dict = {"Fruit":"Pear", "Vegetable":"Carrot", "Pet":"Cat", "Book":"Moby dick", "Crystal":"Amethyst"}
0 is a key value pair where “city” is the key and “Seoul” is its value.
Here is the syntax to declare a dictionary in Python:
my_dict = { <key>: <value>, <key>: <value>, . . . <key>: <value> }
In examples, we will use the dictionary below:
>>> # Declare a dictionary >>> my_dict = {"Fruit":"Pear", "Vegetable":"Carrot", "Pet":"Cat", "Book":"Moby dick", "Crystal":"Amethyst"}
Declare a dictionary named my_dict:
>>> print(my_dict) {'Fruit': 'Pear', 'Vegetable': 'Carrot', 'Pet': 'Cat', 'Book': 'Moby dick', 'Crystal': 'Amethyst'} >>> >>>
How to remove a key from a python dictionary
Remove the key using del. The del keyword used to delete the key. The syntax is as follows:
del dict["Key"]
Let’s delete a key in our dictionary my_dict. We will remove the key: “Fruit”:
# Delete a key – Fruit
>>> >>> del my_dict["Fruit"] >>> >>> >>> print(my_dict) {'Vegetable': 'Carrot', 'Pet': 'Cat', 'Book': 'Moby dick', 'Crystal': 'Amethyst'} >>>
We can observe that after removing that key, the key “Fruit” is no longer visible in the dictionary. But what if you want to remove a key that doesn’t exist?
Try deleting the Fruit key again.
>>> >>> del my_dict["Fruit"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Fruit' >>> >>>
We got a tracking error. Because the key does not exist, this is correct. Dell has a drawback that it throws an exception when the key is not found. Exceptions must be handled explicitly in the try-catch block. However, this exception handled by the second way.
Use Python.pop() to remove the key from the dictionary
The Python.pop() method is extremely handy for retrieving a dictionary entry and removing its key from the dictionary.
The Python.pop() function works as follows:
dictionary.pop(key, default_value)
The first input is the key to be removed, and the second (optional) parameter is the value that will be returned if the key does not exist.
When you use this, you get three outcomes.
pop() function:
- If the key is found in the dictionary, the value of the key is returned and the key is deleted from the dictionary.
- If the key does not exist and a default value is supplied, the default value is returned.
- If the key does not exist and no default value is specified, a KeyError is thrown.
Let’s see how we can use the Python.pop() dictionary method to remove keys from our dictionary:
# Delete a key using .pop() a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35} a_dict.pop('John') print(a_dict) # Returns: {'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
Let’s examine what happens if we try to remove a non-existent key:
# Delete a key that doesn't exist using .pop() a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35} a_dict.pop('Jamie') print(a_dict) # Returns: KeyError: 'Jamie'
We may supply a default value into our if we wish to securely delete a key from the dictionary, meaning no error is generated. pop() function. A good default would be return None, as it allows us to simply continue.
# Delete a key that doesn't exist using .pop() a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35} a_dict.pop('Jamie', None) print(a_dict) # Returns: {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
We can see that by using.pop(), we may securely delete the key from the Python dictionary. Let’s look at how we may use the del keyword to delete a key from the dictionary.
How to Remove Multiple Keys from a Python Dictionary
Python makes removing numerous keys from a dictionary simple. Therefore, the most secure solution is to cycle over a list of keys and use the.pop() function.
Let’s look at how we may give in a list of keys to remove, even ones that don’t exist:
# How to remove multiple keys from a Python dictionary a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35} keys = ['John', 'Mary', 'Mel'] for key in keys: a_dict.pop(key, None) print(a_dict) # Returns: {'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
It’s worth noting that we use. None as the default value to ensure that no KeyError is triggered when a key doesn’t exist.
CONCLUSION
To sum up, in this article we have fully shown you the ways to remove keys in python using the .pop() method, the del keyword. Moreover, at the end we even show you how to safely delete multiple keys from a python dictionary. If you are new to python and are looking for a way to delete key from dictionary python then here we have everything you need.
To provide high-quality Mobile Application Development services, ONEXT DIGITAL has a team of specialists and experienced developers who use cutting-edge technology. We will give you the highest level of satisfaction possible.
>> Read also: