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

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

Now we want to remove an item from dictionary whose key is “at”. Let’s see how to do that,

Remove a key from dictionary using del

del statement removes the given item from the dictionary. If given key is not present in dictionary then it will throw KeyError.

Let’s use it to remove the key from above mentioned dictionary,

Output:

It’s necessary to check if key is present in dictionary before deletion otherwise del with throw keyError.

Deleting key from dictionary using del and try/except

If we don’t want of add if check before calling del, we can use try/except too. Let’s try to delete a key that does not exist in dictionary and catch the error too i.e.

Output:

Remove a key from dictionary using dict.pop()

  • If key exists in dictionary then dict.pop() removes the element with given key from dictionary and return its value.
  • If given key doesn’t exist in dictionary then it returns the given Default value.
  • If given key doesn’t exist in dictionary and No Default value is passed to pop() then it will throw KeyError

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

Output:

Let’s delete an element that is not present in dictionary using pop()

Output:

It will return given default value i.e. None

Default value in pop() is neccesary, because if given key is not present in dictionary and no default value is given in pop() then it will throw keyError.

Deleting key from dictionary using pop() and try/except

Let’s delete an element that is not present in dictionary using pop() and without passing default value argument in pop() i.e.

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.