Remove key from dictionary in Python

In this Python tutorial, I will explain How to remove key from dictionary in Python. We will see what a Python dictionary is. What are the different methods to remove a key from dict Python with some illustrative examples and some points to consider while removing the keys in dict Python?

Python is one of the most widely used programming languages around the world. One of the basic and useful data structures in Python is the dictionary.

A dictionary in Python is an unordered collection of data values, used to store data values like a map. It comprises key-value pairs and uses the key to access the value associated with that key.

Example:

state_capitals = {
    'California': 'Sacramento',
    'New York': 'Albany',
    'Texas': 'Austin',
    'Florida': 'Tallahassee'
}

print(type(state_capitals))

In this example, states like California and New York are the keys, and Sacramento and Albany are their respective values.

The Output is:

<class 'dict'>
Remove key from dictionary Python

This way, we can create dict in Python.

Remove key from dictionary in Python

There are four different ways to remove keys from a Python dict.

  • the del statement
  • the pop() method
  • Dictionary Comprehension
  • the popitem() method

Let’s see them one by one using illustrative examples:

Method-1: Python dictionary remove key using the del statement

The del statement deletes a key-value pair based on the specified key from a Python dict. It is useful when we know the exact dict key Python, we want to remove.

The syntax of the del statement in Python is:

del dictionary_name['key_name']

For instance, Imagine we’re maintaining a Python dictionary of the top cities and their nicknames. But now we want to remove New York, the “Big Apple”.

city_nicknames = {
    'Chicago': 'The Windy City',
    'Los Angeles': 'City of Angels',
    'New York': 'The Big Apple',
    'San Francisco': 'The Golden Gate City'
}

del city_nicknames['New York']
print(city_nicknames)

The output is:

{'Chicago': 'The Windy City', 'Los Angeles': 'City of Angels', 'San Francisco': 'The Golden Gate City'}
python dict delete key using del statement

With the del statement, the key ‘New York’ is removed from the dictionary Python.

Method-2: Python remove key from dictionary using the pop() method

The pop() method removes a Python dict key based on the provided key and returns the associated value. It is handy when we need the removed key’s value for further operations.

The syntax of the pop() method in Python is:

value = dictionary_name.pop('key_name', default_value)

For example, Say we have a Python dictionary of states and their mottos, and we want to remove ‘Michigan’, known as the “If you seek a pleasant peninsula, look about you”, and keep its motto for reference.

state_mottos = {
    'California': 'Eureka',
    'Texas': 'Friendship',
    'New York': 'Excelsior',
    'Michigan': 'If you seek a pleasant peninsula, look about you'
}

removed_motto = state_mottos.pop('Michigan')
print(f"Removed motto: {removed_motto}")
print(state_mottos)

The Output is:

Removed motto: If you seek a pleasant peninsula, look about you
{'California': 'Eureka', 'Texas': 'Friendship', 'New York': 'Excelsior'}
python dictionary remove key using pop() method

The pop() method in Python dict remove the key ‘Michigan’ and returns its motto, “If you seek a pleasant peninsula, look about you”

Method-3: Python remove key from dict using dictionary comprehension

The dictionary comprehension in Python allows us to create a new Python dictionary by iterating over an existing one, filtering out unwanted keys in the process. It is Ideal for removing multiple keys from dict Python based on a condition or set of conditions.

The syntax of dictionary comprehension in Python is:

new_dict = {k: v for k, v in old_dict.items() if condition}

For instance, Imagine we have a dictionary of states and their highest points. Using dictionary comprehension, we want to retain only the states that aren’t part of the Mountain States.

state_highest_points = {
    'Colorado': 'Mount Elbert',
    'Arizona': 'Humphreys Peak',
    'Florida': 'Britton Hill',
    'New York': 'Mount Marcy'
}

non_mountain_states = {key: value for key, value in state_highest_points.items() if key not in ['Colorado', 'Arizona']}
print(non_mountain_states)

The Output is:

{'Florida': 'Britton Hill', 'New York': 'Mount Marcy'}
python dict remove key using dict comprehension

By using dictionary comprehension in Python, only the states outside of the Mountain States region are retained by creating a list of the keys to be removed.

Method-4: Python remove key from dict using the popitem() method

The popitem() method removes and returns the last key added to the Python dictionary as a tuple. It is useful when we want to process and remove dict keys in a last-in, first-out manner.

The syntax of the popitem() method in Python is:

last_item = dictionary_name.popitem()

For instance, If we’re cataloging national parks and their states, we might want to remove the last added park as a key from the Python dictionary using the popitem() method in Python:

national_parks = {
    'Great Smoky Mountains': 'Tennessee',
    'Grand Canyon': 'Arizona',
    'Rocky Mountain': 'Colorado',
    'Zion': 'Utah'
}

last_park, its_state = national_parks.popitem()
print(f"Removed {last_park} located in {its_state}.")
print(national_parks)

The output is:

Removed Zion located in Utah.
{'Great Smoky Mountains': 'Tennessee', 'Grand Canyon': 'Arizona', 'Rocky Mountain': 'Colorado'}
dict remove key in python using popitem() method

The popitem() method effectively del in Python the last added dict key, in this case, Zion National Park in Utah is removed from the Python dictionary.

Read: Filter Dictionary Python [3 Methods+ Examples]

Points for Consideration in Python Remove key from dictionary

  • KeyError: If we try to remove a key in the Python dictionary that doesn’t exist using the del statement or the pop() method (without a default value), a KeyError will be raised. Always ensure the key exists before removal or provide a default value with the pop() method in Python.
  • Mutability: Remember that dictionaries in Python are mutable. So, when we remove a key, it’s removed from the original Python dictionary, unless we’re working on a copy of that Python dictionary.

Conclusion

Here, we have seen how to remove key from dictionary Python using four different methods like del statement, pop() method, dictionary comprehension, and popitem() methods using demonstrative examples. We have also seen some points for consideration while removing the Python dictionary key from some methods.

You may also like to read: