Python Delete Key
Assume you use a Python dictionary with the students' roll numbers as keys to store the names of the students in your class.
In Python, a dictionary is nothing more than a set of key-value pair mappings.
For instance:
Aman Kumar in 1601.
Roshni Jain in 1602
Utkarsh Rajput in 1603
Kritika Grover, 1699
Imagine that some of your pupils are required to drop your class or desire to switch schools. You must do this in order to protect the privacy of your current students' records. In other words, you need to get rid of the dictionary key that corresponds to the departing student's roll number.
Remove the key from the dictionary in Python may be done in a number of methods, including
Method 1: Remove a Key from a Dictionary Using pop()
Using the pop () function on a dictionary object, such as dict, you may remove key from the dictionary in Python. It returns the value associated with the key after removing the provided key (and its corresponding value) from the dictionary.
Syntax:
# dict is a sample dictionary
# Syntax 1
dict.pop(key)
# Syntax 2
returnedValue = dict.pop(key)
# Syntax 3
dict.pop(key, defaultVal)
# Syntax 4
returnedValue = dict.pop(key, defaultVal)
Please be aware:
The pop() function returns the value after removing the key-value pair for the given key in all of its variants.
defaultVal, the second parameter, is optional. When the key provided cannot be found in the dictionary, it is returned.
If the second parameter is left out and the key cannot be found in the dictionary (on which the.pop() method is called), KeyError will be raised.
Other acceptable options for the second argument are None, -1, 0, etc.
Example 1 of a Code:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
dict.pop(1601)
print("Dictionary:", dict)
removedName = dict.pop(1603)
print("Removed Student: ", removedName)
print("Dictionary:", dict)
removedName2 = dict.pop(1600, "No such roll number found!")
print("Removed Student:", removedName2)
print("Dictionary:", dict)
Output:
Dictionary: {1602: 'Roshni', 1603: 'Utkarsh', 1699: 'Kritika'}
Removed Student: Utkarsh
Dictionary: {1602: 'Roshni', 1699: 'Kritika'}
Removed Student: No such roll number found!
Dictionary: {1602: 'Roshni', 1699: 'Kritika'}
Explanation:
It was successfully deleted since we used the key parameter 1601 and it was already in the dictionary.
The return value from removing 1603 was then stored in removedName so that we could later confirm the key-value pair that had been removed.
After that, we gave a default value that will be used if the dictionary does not include the key we wish to remove.
We receive the text "No such roll number found" as the output since the key 1600 does not exist in the dict.
Example of Code 2:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
# trying to remove a key
# that does not exist
dict.pop(1600)
Output:
Traceback for a key error (last call is from most recent)
Documents/Computer Programs at home/amanRemove Key From Cell 2 in Python.ipynb (cell line: 5)()
1 dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
3 # trying to remove a key
4 # that does not exist
----> 5 dict.pop(1600)
KeyError: 1600
As previously said, we receive a KeyError since the key 1600 is not present in the dictionary.
Method 2: Try/Except Block and pop()
To deal with any exceptions that can arise when running a block of code, utilize try-except blocks.
A try block encloses a block of code that needs to be run. The code that must be executed in the case of an exception is found in the unless block. More information regarding try-except blocks may be found here.
Python's try-except block may be used to remove the key from the dictionary using the following syntax:
Syntax:
dict is some dictionary
tKey is the target key to be deleted
try:
dict.pop(tKey)
except:
print("Key Not Found!")
Code Example 1:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
try:
retVal2 = dict.pop(1600)
print(retVal2)
except:
print("Key Not In Dictionary")
Output:
Not In Dictionary for Key
The dictionary's key 1600 was tried to be deleted by the malware. However, because the key wasn't in the dictionary, a KeyError exception was produced, which the except block captured and ran the code inside of.
Please take note that the exception can be specified in the code as follows:
Try this except for (KeyError):
Print ("Key Not In Dictionary")
Both of the code pieces in the aforementioned example are identical to having Python remove the key from the dictionary.
Method 3: For-Loops and the items () method
Python's items () function may be combined with a for-loop to delete a key from the dictionary. All key-value pairs (except from the key that has to be erased) are simply copied from our existing dictionary to our new dictionary by iterating over it.
Finally, we assign our old dictionary variable with this new dictionary.
To remove the key from the dictionary, use Python's items function. The syntax is as follows:
Syntax:
The dictionary is #dict, and the key to be erased is #tKey.
temp_dict = {}
for k, v in dict.items():
if k != tKey:
temp_dict[k] = v
dict = temp_dict
Code Example 1:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
target_key = 1602
temp_dict = {}
for k,v in dict.items():
if k != target_key:
temp_dict[k] = v
dict = temp_dict
print("Dictionary:" , dict)
Output:
Dictionary: {1601: 'Aman', 1603: 'Utkarsh', 1699: 'Kritika'}
When iterating over the dictionary, just the key that was to be deleted was transferred into our temporary dictionary temp_dict.
We then assigned our dict variable to the updated dictionary, which does not include the key that was removed.
In the absence of the target key, this process would have basically replicated the dictionary in its entirety, and no change would have been seen.
Technique #4: Using objects () Procedure & Dictionary Comprehensions
A method of iterating through a dictionary without utilizing loops is dictionary comprehension. Learn more about Python comprehension by visiting this page. Again, we just duplicate the key-value pairs into our own dictionary via reassignment (apart from the key that has to be erased).
The following syntax is used in Python code to delete the key from the dictionary using the items method and dictionary comprehensions:
The dictionary is #dict, and the key to be erased is #tKey.
dict = { key:val
for key, val
in dict.items()
if key!=tKey }
Code Example 1:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
target_key = 1602
dict = { key: value
for key, value
in dict.items()
if key != target_key}
print("Dictionary:" , dict)
Output:
Dictionary: {1601: 'Aman', 1603: 'Utkarsh', 1699: 'Kritika'}
We employ the following syntax by utilizing the items technique and dictionary comprehensions.
We created a dictionary without the target key that would be eliminated using dictionary comprehensions, and we assigned our variable dict to the newly created dictionary.
Method 5: Using the Del keyword
A key from a dictionary can be removed using the Python del keyword. The del keyword merely eliminates the variable's reference, making it unoccupied in memory.
If the key wasn't found in the dictionary, the program would raise the KeyError exception.
The syntax for removing a key from a dictionary using Python's del keyword is as follows:
dict is a dictionary in syntax
The target key to be erased is tKey.
del dict[tKey]
Using the above statement, we can delete the key from the dictionary in Python.
Code Example 1:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
target_key = 1602
del dict[target_key]
print("Dictionary:" , dict)
Output:
Dictionary: {1601: 'Aman', 1603: 'Utkarsh', 1699: 'Kritika'}
Explanation: Since the key 1602 was present in the dictionary, therefore using del dict[key] removed the key from the dictionary.
Code Example 2
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
target_key = 1604
try:
del dict[target_key]
except:
print("Key Not Found!")
print("Dictionary:" , dict)
Output:
Key Not Found!
Dictionary: {1601: 'Aman', 1602: 'Roshni', 1603: 'Utkarsh', 1699: 'Kritika'}
We employ the following syntax by utilizing the items approach and dictionary comprehensions:Reason: Because the key 1604 wasn't in the dictionary, using the del keyword resulted in a KeyError exception.
As a result, the except block received control of the program, and the print statement was executed there to generate the output that was displayed.
Taking out All Keys Using the Python Dictionary's clean () Method
To delete all the keys (and corresponding values) from a particular dictionary, we may utilize the clear() function of the dictionary class.
Please take note that using the dictionary's clear () function results in an empty dictionary rather than a none object. See the illustration below.
The clear () function in Python is used to delete a key from the dictionary.
Syntax:
# dict is some dictionary
# tKey is the target key to be deleted
dict.clear()
Code Example:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
dict.clear()
print("Dictionary:" , dict)
print("Type: ", type(dict))
Output:
Dictionary: {}
Type: <class 'dict'>
Explanation:
The key-value pairs in the dictionary are all deleted when the clear () function is used on the dictionary dict.
Not a none object, but an empty dictionary is produced by the call to clean ().
Taking Out All Keys Using Python Dictionary's popitem() method
In Python, you may delete and return keys from a dictionary in LIFO (last in first out) order by using the popitem() function. All keys in the Python dictionary are eliminated by repeatedly using this function until it returns empty.
A dictionary item is removed using the pop() function in Python.
The removal of items from a list at a certain index value may likewise be accomplished using this technique. We'll concentrate on eliminating a term from a dictionary in this manual. In this course on the Python list pop() method, we go into further depth on how to remove an item from a list.
This method's syntax is as follows:
not_found, key_to_remove, dictionary.pop
One or two arguments may be sent to the pop() method:
What key's name do you want to remove? (mandatory).
The value that ought to be returned in the absence of a key (optional).
The following syntax is used to delete a key from a dictionary in Python using the popitem() method:
Syntax:
# dict is some dictionary
while(len(dict)):
dict.popitem()
This results in dict being an empty dictionary (and not a None object).
Code Example 1:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
while(len(dict)):
x = dict.popitem()
print(x)
print("Dictionary:" , dict)
Output:
(1699, 'Kritika')
(1603, 'Utkarsh')
(1602, 'Roshni')
(1601, 'Aman')
Dictionary: {}
Using popitem() removes key-value pairs in a LIFO method, as explained. The dictionary is empty once all such pairs have been deleted, as can be seen from the output.
Python Dictionary Multiple Keys Removed
Python offers an iterative method for deleting many keys from a dictionary.
The pop() function may be used to remove keys by using it on each member of a list that contains the desired keys.
Syntax:
# dict is some dictionary
# keys_to_remove is a list of keys to be removed
for tKey in keys_to_remove:
dict.pop(tKey)
Code Example:
dict = {1601:"Aman", 1602: "Roshni", 1603: "Utkarsh", 1699:"Kritika"}
keys_to_remove = [1602, 1603]
for tKey in keys_to_remove:
dict.pop(tKey)
print("Dictionary:" , dict)
Output:
Dictionary: {1601: 'Aman', 1699: 'Kritika'}
When the pop() method is repeatedly performed on the dictionary dict, all of the keys that were listed in the keys_to_remove list are eliminated.
pop() vs del in Python
In Python, the del keyword and the pop() function may both be used to delete keys from dictionaries. (as we saw above). The sole distinction between these two approaches is that the deleted key is not returned when the del keyword is used.
To delete a key from the Python dictionary, the following piece of code would not be acceptable.
removedKey = del dict[tKey]
The following Python code is legal since the pop() function returns the value of the key that was deleted:
# method 1
removedVal = dict.pop(tKey)
# method 2
removedVal = dict.pop(tKey, "Key Not Present!")
Conclusion
A Python dictionary is used to hold key-value pair mappings that are iterable and indexable via keys.
The pop() function returns the value that was removed together with the key that was deleted from the Python dictionary for a specified key. It is possible to encapsulate the KeyError exception in a try-except block to capture it.
Using the del keyword is another way to delete a key from the Python dictionary. The value that was deleted from the dictionary is not returned by this procedure.
If a KeyError exception arises, a try-except block may be added around it to handle it.
The leftover dictionary items can be copied into a new dictionary and iterated over using a for-loop or dictionary comprehension to get rid of a key-value combination.
Both the popitem() and pop() methods may be used in a loop to delete many keys from a Python dictionary.
Use the clear() method to delete every key-value pair from the dictionary.