How to delete key value pair from dictionary in python

Dictionary is used in manifold practical applications such as day-day programming, web development, and AI/ML programming as well, making it a useful container overall. Hence, knowing shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals with one such task of deleting/removing a dictionary key-value pair from a dictionary, we will discuss different methods to deal given task, and in Last we will see how can we delete all keys from Dictionary.

Example:

Before remove key:   {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}

Operation Perform:   del test_dict['Mani']

After removing key:  {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}

Method 1: Remove a Key from a Dictionary using the del

The del keyword can be used to in-place delete the key that is present in the dictionary in Python. One drawback that can be thought of using this is that it raises an exception if the key is not found and hence non-existence of the key has to be handled. Demonstrating key-value pair deletion using del.

Python3

test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}

print("The dictionary before performing remove is : ", test_dict)

del test_dict['Mani']

print("The dictionary after remove is : ", test_dict)

del test_dict['Mani']

Output :

The dictionary before performing remove is :  {'Arushi': 22, 'Mani': 21, 'Haritha': 21}
The dictionary after remove is :  {'Arushi': 22, 'Haritha': 21}

Exception : 

Traceback (most recent call last):
  File "/home/44db951e7011423359af4861d475458a.py", line 20, in 
    del test_dict['Mani']
KeyError: 'Mani'

Method 2: Remove a Key from a Dictionary using pop() 

The pop() can be used to delete a key and its value inplace. The advantage over using del is that it provides the mechanism to print desired value if tried to remove a non-existing dict. pair. Second, it also returns the value of the key that is being removed in addition to performing a simple delete operation. Demonstrating key-value pair deletion using pop() 

Python3

test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

print("The dictionary before performing remove is : " + str(test_dict))

removed_value = test_dict.pop('Mani')

print("The dictionary after remove is : " + str(test_dict))

print("The removed key's value is : " + str(removed_value))

print('\r')

removed_value = test_dict.pop('Manjeet', 'No Key found')

print("The dictionary after remove is : " + str(test_dict))

print("The removed key's value is : " + str(removed_value))

Output:

The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21,
 'Mani': 21, 'Haritha': 21}
The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : 21

The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : No Key found

Method 3: Using items() + dict comprehension to Remove a Key from a Dictionary

items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion but, it has the drawback of not being an in-place dict. technique. Actually, a new dict is created except for the key we don’t wish to include. Demonstrating key-value pair deletion using items() + dict comprehension.

Python3

test_dict = {"Arushi": 22, "Anuradha": 21,

             "Mani": 21, "Haritha": 21}

print("The dictionary before performing\

remove is : " + str(test_dict))

new_dict = {key: val for key,

            val in test_dict.items() if key != 'Mani'}

print("The dictionary after remove is : " + str(new_dict))

Output:

The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}

Method 4: Use a Python Dictionary Comprehension to Remove a Key from a Dictionary

In this example, we will use Dictionary Comprehension to remove a key from a dictionary.

Python3

test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

print("The dictionary before performing remove is : \n" + str(test_dict))

a_dict = {key: test_dict[key] for key in test_dict if key != 'Mani'}

print("The dictionary after performing remove is : \n", a_dict)

Output:

The dictionary before performing remove is : 
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
The dictionary after performing remove is : 
 {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}

Method 5: Iterating and Eliminating

In this example, we will use a loop to remove a key from a dictionary.

Python3

test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

print(test_dict)

y = {}

for key, value in test_dict.items():

    if key != 'Arushi':

        y[key] = value

print(y)

Output:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
{'Anuradha': 21, 'Mani': 21, 'Haritha': 21}

How to Delete all Keys from a Dictionary?

Method 1: Delete all Keys from a Dictionary using the del

The del keyword can also be used to delete a list, slice a list, delete dictionaries, remove key-value pairs from a dictionary, delete variables, etc.

Python3

test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

print(test_dict)

del test_dict

try:

    print(test_dict)

except:

    print('Deleted!')

Output:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
Deleted!

Method 2: Delete all Keys from a Dictionary using dict.clear()

The clear() method removes all items from the dictionary. The clear() method doesn’t return any value.

Python3

test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

print(test_dict)

test_dict.clear()

print("Length", len(test_dict))

print(test_dict)

Output:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
Length 0
{}

Can we remove key value pair from dictionary Python?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

How do you remove a key pair from a dictionary?

There are several ways to remove a key: value pair from a dictionary..
Using del. The del keyword deletes a key: value pair from a dictionary. ... .
Using popitem() The in-built function popitem() deletes the last key: value pair in a dictionary. ... .
Using pop().

How do I remove a specific key from a dictionary in Python?

The del keyword can be used to in-place delete the key that is present in the dictionary in Python. One drawback that can be thought of using this is that it raises an exception if the key is not found and hence non-existence of the key has to be handled.

What is the best way to remove a dictionary item by value in Python?

Use del to remove an item from a dictionary by its value Create a for-loop to iterate through the list of key-value pairs. At each iteration, check if the value is the desired value to remove. If it is, use the del keyword along with dictionary indexing to delete the key-value pair and then call the break keyword.