How to remove a key from a python dictionary?



A dictionary in Python is a collection of key-value pairs. In a few cases, we may have to remove a key and its associated value from a dictionary. Python provides multiple ways to do this safely and efficiently.

Using pop() method

The pop() method is used to remove the specified key and returns the corresponding value. If the key does not exist, then it raises a KeyError unless a default value is provided.

Example

Following is an example, which shows how to remove a key from the dictionary using the pop() method -

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print(my_dict)
print("Removed value:", value)

Following is the output of the above example -

{'a': 1, 'c': 3}
Removed value: 2

Using the del keyword

The del keyword in Python removes a key-value pair by using the key of the dictionary. It raises a KeyError if the key doesn't exist.

Example

Following is the example which uses the del keyword to remove the key from the dictionary -

my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']
print(my_dict)

Below is the output of the above program -

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

To avoid raising errors, we need to check if the key exists before deleting it by using the if statement -

my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'd' in my_dict:
   del my_dict['d']
print(my_dict)

Using popitem() method

The popitem() method in Python is used to remove and return the last key-value pair inserted from Python 3.7+ versions.

Example

Following is an example of using the popitem()method to remove the last key-value pair of the dictionary -

my_dict = {'a': 1, 'b': 2, 'c': 3}
item = my_dict.popitem()
print("Removed:", item)
print(my_dict)

Here is the output of the above example -

Removed: ('c', 3)
{'a': 1, 'b': 2}

Using Dictionary Comprehension

We can use dictionary comprehension to create a new dictionary, excluding specific keys to remove them from the dictionary.

Example

In the following example, we are using the dictionary Comprehension to remove the specific key -

my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {k: v for k, v in my_dict.items() if k != 'b'}
print(new_dict)

Below is the output of the above program -

{'a': 1, 'c': 3}
Updated on: 2025-05-28T14:52:59+05:30

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements