How to Remove a Key From a Dictionary in Python

  1. Delete Key From Dictionary Using the pop() Function in Python
  2. Remove Key From Dictionary Using the del Keyword in Python

This article will introduce methods to remove a key from a dictionary in Python, like the pop() function and the del keyword.

Delete Key From Dictionary Using the pop() Function in Python

We can use the built-in Python function pop() to delete a key from a dictionary. The correct syntax of this method is:

mydict.pop(key[, default])

The detail of this function is as follows:

Parameters Description
key mandatory It is the key that we want to remove from our dictionary. If the key doesn’t exist in the dictionary, it returns the default value. If the default value is not passed, it raises an error.

This function returns the specified key and meanwhile deletes it from the dictionary if it exists. Otherwise, it returns the default value.

The program below shows how we can use this function to remove a key from a dictionary in Python.

mydict = {
  "1": "Rose",
  "2": "Jasmine",
  "3": "Lili",
  "4": "Hibiscus"
}
print(mydict.pop('2', None))
print(mydict)

Output:

Jasmine
{'1': 'Rose', '3': 'Lili', '4': 'Hibiscus'}

The function has removed the key 2 that has the value as Jasmine.

Now if we try to remove a key that does not exist, then the function will give the following output:

mydict = {
  "1": "Rose",
  "2": "Jasmine",
  "3": "Lili",
  "4": "Hibiscus"
}
print(mydict.pop('5', None))

Output:

None

The function has returned the default value.

Remove Key From Dictionary Using the del Keyword in Python

We can also use the del keyword to remove a key from a dictionary in Python. The correct syntax to use this keyword is as follows:

del objectName

The detail of it is as follows:

Parameters Description
objectName mandatory It is the object that we want to delete. It can be any data type or data structure.

The program below shows how we can use this keyword to remove a key from a dictionary in Python.

mydict = {
  "1": "Rose",
  "2": "Jasmine",
  "3": "Lili",
  "4": "Hibiscus"
}
del mydict['3']
print(mydict)

Output:

{'1': 'Rose', '2': 'Jasmine', '4': 'Hibiscus'}

The del keyword has removed key 3 that has the value as Lili.

Now, Let’s try to remove a key that does not exist.

mydict = {
  "1": "Rose",
  "2": "Jasmine",
  "3": "Lili",
  "4": "Hibiscus"
}
del mydict['5']
print(mydict)

Output:

KeyError: '5'

It throws a KeyError.

Related Article - Python Dictionary

  • How to Get Dictionary Keys as a List in Python