How to remove a key without an error in the Python dictionary

In this Python tutorial, we will see how to remove a key without an error in the Python dictionary. To remove keys without any error in a Python dictionary we will see different methods with examples.

A Python dictionary is a built-in data type that allows the storage of data in key-value pairs. Keys in a dictionary are unique, and each key points to a value. The removal of the key is a very common operation done in a Python dictionary.

Regular Removal of a Key in Python Dictionary

In Python, we can remove a key from a dictionary using the del keyword followed by the dictionary name and the key inside square brackets. Here, we have the USA landmark’s details.

us_landmarks = {
    'Statue of Liberty': 'New York',
    'Mount Rushmore': 'South Dakota',
    'Golden Gate Bridge': 'California',
    'Grand Canyon': 'Arizona',
    'White House': 'Washington, D.C.'
}

del us_landmarks['White House']

The line of code above will remove the ‘White House’ and its corresponding value from the dictionary.

However, if we attempt to remove a key that does not exist in the dictionary, we will get a KeyError. See what if we extend the above example:

del us_landmarks['Lincoln Memorial']

Output is:

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 10, in <module>
    del us_landmarks['Lincoln Memorial']
        ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
KeyError: 'Lincoln Memorial'
How to remove a key without an error in the python dictionary

So, to safely remove a key from a Python dictionary without any Error.

Removing a key without an error in the Python dictionary

There are several different ways to safely remove keys from a Python dictionary without any error:

  • Using the dict.pop(key, default) Method
  • Using dict.get(key) with del
  • Using dict.setdefault(key) Method
  • Using try-except Block
  • Using Dictionary Comprehension

Method-1: Using the Python dict.pop(key, default) method

The pop() method from the dict class in Python will remove a key from the dictionary and return its value. If a second argument is provided to the pop() method, it will return that value if the key is not found in the dictionary.

Here, we have a dictionary that contains the number of states in different regions of the USA:

region_dict = {
    'West': 13,
    'Midwest': 12,
    'South': 17,
    'Northeast': 9
}

region_dict.pop('Midwest', None)

As output, nothing will be there.

safely removing key from a python dictionary without error using dict.pop()

Read: How to handle KeyError with Try-Except in a Python dictionary

Note: This is only valid for the key in the Python dictionary. The key which does not exists will give KeyError.

Method-2: Using Python dict.get(key) with del method

One way to remove a key without raising an error in the Python dictionary is by checking if the key exists in the dictionary before attempting to remove it. You can use the get() method, which returns None if the key is not found, as a safety check.

Here, we have product details with the total amount invested in them as a Python dictionary.

product_dict = {
    'Electronics': 10000,
    'Clothing': 50000,
    'Home Decor': 20000
}

del product_dict['Clothing']

The output for this block of code will also be nothing.

safely removing key from a python dictionary without error using del

Note: This is only valid for the key in the Python dictionary. The key which does not exists will give KeyError.

Method-3: Using Python dict.setdefault(key) Method

The setdefault() function in Python is used to set a default value if a key does not exist in the dictionary. However, we can use this function to safely attempt to remove a key.

Here, we have a Python dictionary that stores the number of orders for different categories of products in a U.S. e-commerce platform:

order_dict = {
    'Electronics': 10000,
    'Clothing': 50000,
    'Home Decor': 20000,
    'Books': 30000,
    'Sports': 15000
}

if order_dict.setdefault('Books'):
    del order_dict['Books']

The output for this block of code will also be nothing.

safely removing key from a python dictionary without error using setdefault()

Note: This is only valid for the key in the dictionary. The key which does not exists will give KeyError.

Method-4: Using the Python try-except Block

The try-except block in the Python dictionary is an exception handler. The block of code which can give an error is put under the try block and except block holds the error if occurred and a pile of code that will execute when the occurs happens.

Here, we have a Python dictionary that stores some major U.S. cities’ average temperatures (in Fahrenheit):

temp_dict = {
    'Los Angeles': 75.0,
    'New York': 55.0,
    'Chicago': 52.0,
    'Houston': 70.0,
    'Phoenix': 85.0
}

try:
    del temp_dict['New York']
except KeyError:
    pass

The output for this block of code will also be nothing.

safely removing key from a python dictionary without error using try-except

Method-5: Using Python Dictionary Comprehension

In this method, we will create a Python new dictionary without certain keys using dictionary comprehension. The dict. comprehension constructs a new dictionary from the original one but excludes the key-value pair where the key is not in the dictionary.

Here, we have Gryffindor house details from Harry Potter:

Houses = {
    "Harry Potter": "Gryffindor",
    "Ron Weasley": "Gryffindor",
    "Hermione Granger": "Gryffindor",
    "Albus Dumbledore": "Gryffindor"
}

students = {key: value for key, value in Houses.items()
            if key != 'Albus Dumbledore'}

print('students in Gryffindor houses are: \n', students)

The output we can only see if we print the second dictionary(students):

students in Gryffindor houses are: 
 {'Harry Potter': 'Gryffindor', 'Ron Weasley': 'Gryffindor', 'Hermione Granger': 'Gryffindor'}
safely removing key from a python dictionary without error using dict. comprehension

This way we easily remove the key from one dictionary and will get another dictionary.

Note: if we give the key which is not in the first dictionary, then the whole dictionary will be copied.

Conclusion:

Safely removing keys from a Python dictionary is an essential operation, especially when dealing with dynamic data where we can’t predict the keys’ existence in our dictionary. Remember, each method has its pros and cons, and the choice largely depends on our specific use case and the requirements of our application.

You may like to read: