In python, a dictionary is an unordered collection of data which is used to store data values such as map unlike other datatypes that store only single values. Keys of a dictionary must be unique and of immutable data type such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. Dictionaries are mutable, therefore keys can be added or removed even after defining a dictionary in python.
They are many ways to remove a key from a dictionary, following are few ways.
Using pop(key,d)
The pop(key, d) method returns the value of a key from a dictionary. It accepts two arguments: the key to be removed and an optional value to return if the key cannot be found.
Example 1
Following is an example of using the required key parameter to pop an element.
Output
The following output is generated on executing the above program.
{1: 'a', 2: 'b'}Example 2
In the following example, the popped key value is accessed by assigning the popped value to a variable.
Output
The following output is generated on executing the above program.
{1: 'a', 2: 'b'} {2: 'b'} aExample 3
The following is an example which shows the removal of a key from a dictionary using the del() function. Unlike pop() using dictionary, we can’t return any value using the del() function.
Output
The following output is generated on executing the above program.
{1: 'a', 2: 'b'} {2: 'b'}Using Dict Comprehensions
The preceding techniques update a dictionary while it is still in use, which means the key value pair is deleted. If we need to keep the original key, we can do it with a custom function.
It's general knowledge in Python that list comprehensions can be used to construct a new list from an existing one. We can use dict comprehensions to perform the same thing with dictionaries. Instead of eliminating entries from a list, we can create a new dictionary with a condition that excludes the values we don't want using a dict comprehension.
Example
The following is an example in which a key is removed from a python dictionary using dict comprehensions.
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print("Original Dictionary: ", dict1)
print("Dictionary after using pop(): ", dict1)
print("The value that was removed is: ", valDel)
print("Dictionary after using pop(): ", dict1)
print("The value that was removed is: ", valDel)
valDel = dict1.pop(3, "No Key Found")
print("Dictionary after using pop(): ", dict1)
print("The value that was removed is: ", valDel)
# if default value not given, error will be raised
Now we want to remove an item from this dictionary whose key is “at”. There are different ways to do that. Let’s explore them one by one,
Remove a key from a dictionary using dict.pop()
Advertisements
In Python dictionary class provides a method pop() to delete an item from the dictionary based on key i.e.
- If the given key exists in the dictionary then dict.pop() removes the element with the given key and return its value.
- If the given key doesn’t exist in the dictionary then it returns the given Default value.
- If the given key doesn’t exist in the dictionary and No Default value is passed to pop() then it will throw KeyError
Let’s delete an element from dict using pop(),
Read More:
- Python dict get()
- Python : How to create a list of all the Values in a…
- Pandas: Dataframe.fillna()
- Python dict pop()
Output:
Deleted item's value = 43 Updated Dictionary : {'Hello': 56, 'at': 23, 'test': 43}It deleted the key-value pair from dictionary where the key was ‘this’ and also returned its value.
Related Articles:
- Python dict.pop() method explained in detail
- How to Remove multiple keys from Dictionary while Iterating?
- How to Iterate over all keys of Dictionary in Python?
- How to Iterate over all Values of Dictionary in Python?
Delete a Key from dictionary if exist using pop()
The default value in pop() is necessary, because if the given key is not present in the dictionary and no default value is given in pop() then it will throw keyError. Let’s delete an element that is not present in the dictionary using the pop() function and without passing a default value argument in pop() i.e.
key_to_be_deleted = 'where' word_freq_dict.pop(key_to_be_deleted)Error:
KeyError: 'where'If the given key in pop() function is not present in the dictionary and also default value is not provided, then pop() can throw KeyError. So to avoid that error we should always check if key exist in dictionary before trying to delete that using pop() function and without any default value i.e.
key_to_be_deleted = 'where' if key_to_be_deleted in word_freq_dict: word_freq_dict.pop(key_to_be_deleted) else: print(f'Key {key_to_be_deleted} is not in the dictionary')Output:
Key where is not in the dictionaryWe can also use the try/except to handle that error,
key_to_be_deleted = 'where' try: word_freq_dict.pop(key_to_be_deleted) except KeyError: print(f'Key {key_to_be_deleted} is not in the dictionary')Output:
Key where is not in the dictionaryRemove a key from a dictionary using items() & for loop
Iterate over the key and filter the key which needs to be deleted i.e.
dictionary.pop(key[, default])0Output:
We created a new temporary dictionary and then iterate over all the key-value pairs of the original dictionary. While iterating we copied the key-value pair to new temporary dictionary only if the key is not equal to the key to be deleted. Once the iteration is over, we copied the new temporary dictionary contents to the original dictionary. In this approach there is no risk of KeyError etc.
Remove a key from a dictionary using items() & Dictionary Comprehension
Using the logic of the previous example we can filter the contents of the dictionary based on key using items() & dictionary comprehension,
dictionary.pop(key[, default])2Output:
dictionary.pop(key[, default])1We iterated over the key-value pairs of the dictionary and constructed a new dictionary using dictionary comprehension. But we excluded the pair where key matched the key-to-be-deleted. Then we assigned this new dictionary to the original dictionary. It gave an effect that item from the dictionary is deleted based on key.
Therefore the benefit of this approach is that you need don’t need to worry about the Key Error in case the key does not exist in the dictionary.
Remove a key from a dictionary using del
We can use the del statement to remove a key-value pair from the dictionary based on the key,
dictionary.pop(key[, default])4First select the element from a dictionary by passing key in the subscript operator and then pass it to the del statement. If the key is present in the dictionary then it will delete the key and corresponding value from the dictionary. But if the given key is not present in the dictionary then it will throw an error i.e. KeyError.
Let’s use it to remove the key from the above-mentioned dictionary,
dictionary.pop(key[, default])5Output:
dictionary.pop(key[, default])1It deleted the item from the dictionary where the key was ‘at’. But what if we use a del statement with a key that does not exist in the dictionary, then it can throw KeyError. For example,
dictionary.pop(key[, default])7Output:
KeyError: 'where'Therefore, we should always check if the key exists in the dictionary before trying to delete them using the del keyword to avoid the KeyError,
dictionary.pop(key[, default])9Output:
Key where is not in the dictionaryDeleting a key from a dictionary using del keyword and try/except
If we do not want an if check before calling del, then we can use the try/except too. Let’s try to delete a key that does not exist in the dictionary and catch the error too using try/except,