Delete key from dictionary python: Effective methods to implement it

Are you an app or website developer? If the answer is yes. So you must know a programming language for app/ web development called Python. Because this kind of programming language will give you lots of awesome features. So we know you want to find out more information about it. Therefore, in this blog, ArrowHiTech will bring to you some useful information related to Python. It is the Python dictionary delete key: Effective methods to implement it. In this article, we will share about 6 different methods to delete keys from dictionary python. However, don’t be nervous if you do not know. Because we will move on to the details right now. 

Delete key from dictionary python

Python dictionary delete key using dict.pop()

Firstly, the pop() function in the Python dictionary class allows you to eliminate an item from the dictionary based on its key.

dictionary.pop(key[, default])

  • If the provided key already exists in the dictionary, dict.pop() returns the value of the element with the provided key.
  • In case, the provided key does not exist in the dictionary, the Default value is returned.
  • In case, no default value is specified to pop() and the supplied key does not exist in the dictionary, it will throw a KeyError.

Therefore, let’s use pop to remove an element from the dict () ,

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:

Python dictionary delete key if exist using pop()

The default value in pop() is required because Delete key from dictionary python will be thrown if the given key does not exist in the dictionary and no default value is provided in pop(). Therefore, let’s use the pop() function to delete an element that doesn’t exist in the dictionary, without utilizing the default value parameter.

For example:

key_to_be_deleted = ‘where’

word_freq_dict.pop(key_to_be_deleted)

Error:

KeyError: ‘where’

In case the given key in the pop() function isn’t found in the dictionary, and the default value isn’t specified, pop() may cause a KeyError. To avoid this problem, we should always check if the key already exists in the dictionary before trying to delete it with the pop() function with no default value.

For example:

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

Solution:

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

Python dictionary delete key using items() & for loop

Iterate through the keys, filtering out the ones that need to be removed.

For example:

# 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 built a new temporary dictionary and then iterated over all of the original dictionary’s key-value pairs. Additionally, only if the key is not equal to the key to be deleted did we copy the key-value combination to a new temporary dictionary while iterating. Therefore, we copied the new temporary dictionary contents to the original dictionary after the iteration was completed. So there is no possibility of Delete key from dictionary python using this method.

Remove a key from a dictionary using items() & Dictionary Comprehension

Using the logic from the previous example, we can use items() and dictionary comprehension to filter the dictionary’s contents based on Python dictionary delete key.

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}

Therefore, we used dictionary comprehension to iterate over the dictionary’s key-value pairs and create a new dictionary. However, the pair in which key matched the key-to-be-deleted was excluded. The original dictionary was then assigned to this new dictionary. It had the effect of deleting an item from the dictionary based on the key.

As a result, you won’t have to worry about the Python dictionary delete key Error if the key doesn’t exist in the dictionary if you use this strategy.

Remove a key from a dictionary using del

The del statement can be used to remove a key-value pair from a dictionary based on its key.

del dict[key]

Firstly, the element is selected from a dictionary using the subscript operator. And then passed to the del statement. In case, the key already exists in the dictionary, it will be deleted along with the matching value. However, if the specified key does not exist in the dictionary, an error will be thrown.

For example: Python dictionary delete key

Let’s utilize it to delete the key from the dictionary specified above.

# 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}

Therefore, it removed the item where the key was ‘at’ from the dictionary. However, if we use a del statement with a key that does not exist in the dictionary, KeyError will be thrown. For example,

key_to_be_deleted = ‘where’

del word_freq_dict[“where”]

Output:

KeyError: ‘where’

To avoid the KeyError: Python dictionary delete key, we should always check if the key already exists in the dictionary before deleting it with the del keyword.

# 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

Python dictionary delete key using del keyword and try/except

We may also use try/except if we don’t want to use an if check before calling del. Let’s see if we can delete a key that doesn’t exist in the dictionary while also catching the issue with 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

To conclude that, in this blog, we have already mentioned about Python dictionary delete key. Therefore, hopefully, this article has given you lots of useful information. Additionally, if you want to dig further information. So click right now to CONTACT US or visit our mobile app development services. The ArrowHiTech team is always here to help you. 

Tags

Share