Remove key from Dictionary in Python

In this article we will discuss 6 different ways to delete a key from a dictionary in python.

Suppose we have a dictionary of string and int i.e.

# Dictionary of strings and int
word_freq_dict = {"Hello": 56,
                  "at": 23,
                  "test": 43,
                  "this": 43}

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()

In Python dictionary class provides a method pop() to delete an item from the dictionary based on key i.e.

dictionary.pop(key[, default])

Let’s delete an element from dict using pop(),

key_to_be_deleted = 'this'

# As 'this' key is present in dict, so pop() will delete
# its entry and return its value
result = word_freq_dict.pop(key_to_be_deleted, None)

print("Deleted item's value = ", result)
print("Updated Dictionary :", word_freq_dict)

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.

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 dictionary

We 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 dictionary

Remove 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 of strings and int
word_freq_dict = {"Hello": 56,
                  "at": 23,
                  "test": 43,
                  "this": 43}

key_to_be_deleted = 'at'

new_dict = {}
for key, value in word_freq_dict.items():
    if key is not key_to_be_deleted:
        new_dict[key] = value

word_freq_dict = new_dict

print(word_freq_dict)

Output:

{'Hello': 56, 'test': 43, 'this': 43}

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,

word_freq_dict = {key: value for key, value\
                  in word_freq_dict.items()\
                  if key is not key_to_be_deleted}

print(word_freq_dict)

Output:

{'Hello': 56, 'test': 43, 'this': 43}

We 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,

del dict[key]

First 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 of strings and int
word_freq_dict = {"Hello": 56,
                  "at": 23,
                  "test": 43,
                  "this": 43}

# Deleting an item from dictionary using del
del word_freq_dict['at']

print(word_freq_dict)

Output:

{'Hello': 56, 'test': 43, 'this': 43}

It 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,

key_to_be_deleted = 'where'
del word_freq_dict["where"]

Output:

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,

# If key exist in dictionary then delete it using del.
key_to_be_deleted = 'where'

if key_to_be_deleted in word_freq_dict:
    del word_freq_dict["where"]
else:
    print(f'Key {key_to_be_deleted} is not in the dictionary')

Output:

Key where is not in the dictionary

Deleting 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,

# If key exist in dictionary then delete it using del.
key_to_be_deleted = 'where'

try:
    del word_freq_dict[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 dictionary

Conclusion:

These were the 6 different ways to remove a Key from a dictionary in python.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top