Open In App

Python Remove Key from Dictionary if Exists

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and a key and our task is to remove the key from the dictionary if it exists. For example, d = {"a": 10, "b": 20, "c": 30} and key to remove is "b" then output will be {"a": 10, "c": 30}.

Using pop()

pop() method allows us to remove a key from a dictionary while specifying a default value to handle cases where the key doesn’t exist.

Python
d = {'a': 1, 'b': 2, 'c': 3}

# Removing key 'b' if it exists
d.pop('b', None)

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • pop() method removes the key 'b' if it exists in the dictionary and the None argument prevents errors if the key doesn’t exist.
  • This is an efficient, concise approach for conditional key removal.

Let's explore some more ways and see how we can remove key from dictionary if it exists.

Using del()

The del() keyword can be used to delete a key after confirming its presence with the in operator.

Python
d = {'a': 1, 'b': 2, 'c': 3}

# Checking if key 'b' exists before deleting
if 'b' in d:
    del d['b']

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • 'in' operator checks whether the key 'b' exists in the dictionary.
  • If the key is found, the del statement removes it.

Using dict.get() and del()

We can use get() to check for a key before using del().

Python
d = {'a': 1, 'b': 2, 'c': 3}

# Checking if key 'b' exists
if d.get('b') is not None:
    del d['b']

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • get() method retrieves the value of 'b' if it exists otherwise, it returns None.
  • If the key is found the del statement removes it.
  • This method is slightly less concise compared to del().

Using pop() and try

While pop() can be used directly without a default value, it raises a KeyError if the key doesn’t exist and that is why we use try and except to manage that efficiently

Python
d = {'a': 1, 'b': 2, 'c': 3}

try:
    # Removing key 'b'
    d.pop('b')
except KeyError:
    # Handling the case where the key doesn't exist
    pass

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • This method directly tries to remove the key 'b' using pop().
  • A try-except block handles the KeyError if the key doesn’t exist.

Next Article
Practice Tags :

Similar Reads