Updated November 20, 2023
Introduction to Dictionary Python Remove
Removing, a key from the Python dictionary, is a simple process. It can be implemented by using different dictionary class methods in Python. In Python, dictionaries store information in key-value pairs. To access any value in the dictionary, you can access it via a key.
In Python, dictionaries are mutable objects, meaning you can change the values stored in the dictionaries. Being mutable, you can remove keys from dictionaries anytime whenever they are no longer needed.
For example, you have a dictionary in Python with students data stored in key-value pair mappings. It stores the data that can be accessed using the roll number as keys.
Example:
Code:
<Key> : <Value>
1601: raj
1602: sham
1603: Rita.
Sometimes, you must remove the data, such as a student changing school or subject. With dictionaries, it is easier to remove the required data by removing the key present in the dictionary.
Key Takeaways
The methods below are available for removing an item (element) from a dictionary in Python.
- Using clear() class.
- Removing the item by a key and returning a value using the pop() class.
- Removing an item and returning a key and value using the popitem() class.
- Removing an item by a key from a dictionary using the del keyword.
- Removing the items that meet the condition using Dictionary comprehensions.
How to Remove a Key from a Dictionary?
Different methods are applicable to remove the item from the Python dictionary. This article will highlight dictionary class methods and keywords to help remove the item.
1. Removing items using the clear() method
The clear() method of the dictionary class removes all the keys from the dictionary and makes it empty, not a None object. You can use the following syntax.
dict.clear()
For example:
Code:
dict = {1601:"ajit", 1602: "ram", 1603: "sham", 1699:"sita"}
dict.clear()
print("Dictionary:" , dict)
print("Type: ", type(dict))
Output:
The above output shows that the clear() method on the dictionary deletes all the key-value pairs.
2. Using the pop() method for removing the item by key and returning a value
Another commonly used method is the pop() method, which only removes the key you pass as a parameter to either of the formats. Also, this method will return the value linked with the passed key.
To use this method, you can use any of the following syntaxes based on your requirement.
dict.pop(key)
returnedValue = dict.pop(key)
dict.pop(key, defaultVal)
returnedValue = dict.pop(key, defaultVal)
- Each syntax will eliminate the key-value pair for the specified key/item and return the value linked with that key.
- The defaultVal is optional, but you pass any value to it. This default value will be used if the passed key is not in the dictionary.
- If you do not specify the ‘defaultVal’ parameter and the specified key is not present in the dictionary, then an error named KeyError will display in the output.
- You can use (None, -1, 0) as the viable values for the second parameter.
Example #1
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
dict.pop(1)
print("Dictionary:", dict)
removedName = dict.pop(3)
print("Removed person: ", removedName)
print("Dictionary:", dict)
Output:
Example #2
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
# trying to remove a key
# that does not exist
dict.pop(1600)
Output:
In the above example, the 1600 key is not present. Thus, we get the KeyError.
3. Using the pop() method using the Try/Except Block
You can add try-except blocks that will handle all exceptions if anything goes wrong while removing the specified item/key from the dictionary using the famous pop() method to avoid the error from being raised.
Syntax:
Try:
dict.pop(tKey)
except:
print("Key Not Found!")
Example:
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
try:
retVal2 = dict.pop(1600)
print(retVal2)
except:
print("Key invalid")
Output:
In the above example, the key (1600) is not present, so an error should be raised. The try-catch block handles that.
4. Using the popitem() method
This is the commonly used method of dictionary class for removing the item from the dictionary and returning the key-value pair. In this case, you cannot mention which item you need to remove.
If the dictionary is empty, then a KeyError is raised.
Syntax:
temp_dict = {}
For k, v in dict.items():
if k != tKey:
temp_dict[k] = v
dict = temp_dict
Example:
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
target_key = 2
temp_dict = {}
for k,v in dict.items():
if k != target_key:
temp_dict[k] = v
dict = temp_dict
print("Dict:" , dict)
Output:
5. Using items() method
You can use Dictionary comprehension without needing loops to iterate through all the items within a dictionary. In this method also, you can use reassignment to copy the key-value pairs into the dictionary.
Syntax:
dict = { key:val
for key, val
in dict.items()
if key!=tKey }
Example:
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
target_key = 2
del dict[target_key]
print("Dict:" , dict)
6. Using the ‘del’ keyword
Another way to remove the dictionary item in Python is to use the del keyword. It will simply remove the reference to the item so it will not be in memory. Again, if the item is not present in the dictionary, then a KeyError is raised.
Syntax:
del dict[tKey]
Example:
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
target_key = 2
del dict[target_key]
print("Dict:" , dict)
Output:
If, in case, the key that you want to eliminate is not available in the dictionary, as shown below, you will get an error.
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
target_key = 4
del dict[target_key]
print("Dictionary:" , dict)
Output:
7. Removing multiple keys from the dictionary
To remove multiple keys from a dictionary, you need to do it iteratively. For that, you can store the items to be deleted within a separate list and call the pop() method to remove them one by one.
Syntax:
for tKey in keys_to_remove:
dict.pop(tKey)
Example:
Code:
dict = {1:"ajit", 2: "ram", 3: "sham", 99:"sita"}
keys_to_remove = [2, 3]
for tKey in keys_to_remove:
dict.pop(tKey)
print("Dict:" , dict)
Output:
FAQs
Given below are the FAQs mentioned:
Q1. What does the pop() method do?
Answer: It deletes the key: value pair. For the key that you want to remove, it will delete the pair. It will also return the value of the key passed.
Q2. What does the clear() method do?
Answer: This method will empty the dictionary by deleting all the key-value pairs.
Q3. What error raises in case of removing an invalid key?
Answer: KeyError will be thrown that can be handled using the try-catch block.
Conclusion
Python dictionary stores key-value mutable pair mappings. You can remove a key/item from the Python dictionary using a different method and dictionary classes. The available methods are- clear(), pop(), popitem(), del keyword, items(). Each method removes items, but some return the value associated with the deleted keys. You can combine these methods with a try-catch block to avoid errors from being raised. In this article, we have explained each method with simple examples and output.
Recommended Articles
This is a guide to Dictionary Python Remove. Here we discuss the introduction and how to remove a key from a dictionary. You can also look at the following articles to learn more –