This post will discuss how to remove a key from a dictionary in Python.

1. Using d.pop() function

The standard Pythonic solution to remove a key from the dictionary is using the pop() function.

Download  Run Code

 
If the key is not found in the dictionary, a KeyError is raised. To avoid it, use the two-argument form of pop(key[, default]), which returns the additional default parameter when the key does not exist.

Download  Run Code

 
If you need to remove multiple keys from a dictionary, you can use a list comprehension instead:

Download  Run Code

2. Using del statement

Alternatively, you can use the del d[k] syntax to remove a key k from the dictionary d.

Download  Run Code

 
This raises a KeyError if the key is not in the dictionary. To avoid the exception, use del d[key] with try/except block, as shown below. However, this just adds more complexity to the code. Therefore, the two-arg pop() is recommended over del.

Download  Run Code

That’s all about removing a key from a Python dictionary.