Python json delete key if exists

Approach: calculate keys to remove, mutate dict

Let's call keys the list/iterator of keys that you are given to remove. I'd do this:

keys_to_remove = set(keys).intersection(set(mydict.keys()))
for key in keys_to_remove:
    del mydict[key]

You calculate up front all the affected items and operate on them.

Approach: calculate keys to keep, make new dict with those keys

I prefer to create a new dictionary over mutating an existing one, so I would probably also consider this:

keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: v for k, v in mydict.iteritems() if k in keys_to_keep}

or:

keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: mydict[k] for k in keys_to_keep}

A dictionary is a very powerful data collection in Python. Dictionaries help make database operations faster.

You can append items to an existing dictionary and remove them as well.

In this blog post, we will learn how to delete "keys" using two methods:

  1. Deleting key:value pairs using del.
  2. Deleting key:value pairs using pop().

What is a Dictionary in Python?

A dictionary is an unordered collection of items. The items are defined using key-value pairs. Keys map to their corresponding item in the list. Whenever an item needs to be queried, we can do this using its key.

For example, "city":"Seoul" is a key value pair where "city" is the key, and "Seoul" is its value.

Here's the syntax for declaring a dictionary in Python:

my_dict = {
    : ,
    : ,
      .
      .
      .
    : 
}

In our examples, we will use the below dictionary:

>>> # Declare a dictionary
>>> my_dict = {"Fruit":"Pear", "Vegetable":"Carrot", "Pet":"Cat", "Book":"Moby dick", "Crystal":"Amethyst"}
Declare a dictionary named my_dict
Python json delete key if exists

Remove a key using del.

You can remove a key using the del keyword. Here's the syntax for that:

del dict["Key"]

Let's delete a key in our dictionary my_dict. We'll be deleting the key: "Fruit".

# Delete a key - Fruit
del my_dict["Fruit"]
Python json delete key if exists

After we delete that key, we can see that the key Fruit is no longer present in the dictionary.

But, what happens if you try to delete a key that does not exist?

Let's try to delete the key Fruit again.

Python json delete key if exists
Delete a key that does not exist.

We received a traceback error. This is valid as the key does not exist.

One drawback of del is that it throws an exception when key is not found. The exception needs to be handled explicitly in a try catch block.

However, we can handle this exception using the second method.

Remove a key using pop()

The second way to remove a key is using the pop() method. Here's its syntax:

data.pop("Key", None)

Where,

  • key is the key to be removed.
  • None specifies that if the key is found, then delete it. Else, do nothing.
  • We can also specify a custom message in place of 'None' for cases where key is not found.

Now, if we try to delete Fruit again, there is no exception thrown.

Python json delete key if exists

Now, let's try to delete an existing key with pop().

Python json delete key if exists

Here, the key:Book is successfully deleted.

One advantage of pop() over del is that it allows us to handle exceptions. It provides a mechanism to return a custom message when exception occurs.

How to set a custom message:

Let's try to delete 'Book' again. We are expecting an error, so let's set a return message.

Here, Key does not exist is the return message in case the key does not exist.

my_dict.pop("Book", 'Key does not exist')
Python json delete key if exists
As "Book" was already deleted, we are getting the error message

Another advantage is that it also returns the value of the key in addition to performing a delete operation. If you need to know the value of a deleted key, then pop() is the suitable option.

Python json delete key if exists

Conclusion

In this tutorial, we learned how to create a dictionary in Python. We also focused on how to delete key:value pairs in a dictionary.

I hope you found this tutorial helpful.

Let's connect on Twitter!

Read my other posts here.

Let's chat on Discord.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How do you delete a key in Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.

How do you delete a key

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

How do I remove a key from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method.

How do I delete a key?

Right-click the key and select Delete from the pop-up menu that appears. Select Edit > Keys > Delete Keys. If Time Range-All is on in the Delete Keys options, all keys for the current object are deleted.