Ways to Delete a Dictionary in Python

Python Delete Dictionary

Want to delete a dictionary in Python? The Python Dictionary is a data structure used in Python that accepts elements in key-value pair form. In this article, we will be understanding different Ways of deleting a key-value pair from a Python Dictionary.


The dict.clear() to delete a dictionary in Python

Python has in-built clear() method to delete a dictionary in Python. The clear() method deletes all the key-value pairs present in the dict and returns an empty dict.

Syntax:

dict.clear()

Example:

inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:\n")
print(str(inp_dict))
inp_dict.clear()
print("\nElements of the dict after performing the deletion operation:")
print(str(inp_dict))

Output:

Elements of the dict before performing the deletion operation:

{'B': 'Java', 'D': 'Javascript', 'C': 'Fortan', 'A': 'Python'}

Elements of the dict after performing the deletion operation:
{}

Techniques to delete a key-value pair from a Python Dictionary

The following techniques can be used to delete a key-value pair from a dictionary:

  • Python pop() function
  • Python del keyword
  • In-built Python popitem() method
  • Dictionary Comprehension along with Python items() method

1. Using pop() method

Python pop() method can be used to delete a key and a value associated with it i.e. a key-value pair from a dictionary.

Syntax:

dict.pop(key)

The pop() method basically accepts a key to be deleted from the dictionary. It deletes the key as well as the value associated with the key from the dict and returns the updated dict.

Example:

inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:\n")

print(str(inp_dict))

pop_item = inp_dict.pop("A")

print("\nThe deleted element:")
print(str(pop_item))

print("\nElements of the dict after performing the deletion operation:\n")
print(str(inp_dict))

In the above snippet of code, we have passed the key – “A” as an argument to the pop() method. Thus, it deletes the key value pair associated with “A”.

Output:

Elements of the dict before performing the deletion operation:

{'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}

The deleted element:
Python

Elements of the dict after performing the deletion operation:

{'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}
​

2. Python del keyword

Python del is actually a keyword which is basically used for the deletion of objects. As we all are aware that Python considers everything as an object, that is why we can easily use del to delete a dictionary in Python by deleting elements individually.

Python del keyword can also be used to delete a key-value pair from the input dictionary values.

Syntax:

del dict[key]

Example 1:

inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:\n")
print(str(inp_dict))

del inp_dict["D"]

print("\nElements of the dict after performing the deletion operation:\n")
print(str(inp_dict))

Output:

Elements of the dict before performing the deletion operation:

{'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}

Elements of the dict after performing the deletion operation:

{'A': 'Python', 'B': 'Java', 'C': 'Fortan'}

Example 2: Deleting a key-value pair from a Nested Dictionary

Syntax:

It is possible for us to delete the key-value pair from a nested Python Dictionary. The del keyword serves the purpose with the below syntax:

del dict[outer-dict-key-name][key-name-associated-with-the-value]

Example:

inp_dict = {"Python":{"A":"Set","B":"Dict","C":"Tuple","D":"List"},
             "1":"Java","2":"Fortan"}
print("Elements of the dict before performing the deletion operation:\n")
print(str(inp_dict))

del inp_dict["Python"]["C"]

print("\nElements of the dict after performing the deletion operation:\n")
print(str(inp_dict))

Thus, here, we delete the key-value pair “C:Tuple” associated with the outer key “Python“.

Output:

Elements of the dict before performing the deletion operation:

{'Python': {'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List'}, '1': 'Java', '2': 'Fortan'}

Elements of the dict after performing the deletion operation:

{'Python': {'A': 'Set', 'B': 'Dict', 'D': 'List'}, '1': 'Java', '2': 'Fortan'}

3. Python popitem() method

Python popitem() function can be used to delete a random or an arbitrary key-value pair from a Python dict. The popitem() function accepts no arguments and returns the deleted key-value pair from the dictionary.

Syntax:

dict.popitem()

Example:

inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:\n")
print(str(inp_dict))
pop_item = inp_dict.popitem()
print("\nThe deleted element:")
print(str(pop_item))
print("\nElements of the dict after performing the deletion operation:\n")
print(str(inp_dict))

Output:

Elements of the dict before performing the deletion operation:

{'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}

The deleted element:
('D', 'Javascript')

Elements of the dict after performing the deletion operation:

{'A': 'Python', 'B': 'Java', 'C': 'Fortan'}

4. Python Dict Comprehension along with items() method

Python items() method along with Dict Comprehension can be used to delete a dictionary in Python.

Python items() method basically takes no arguments and returns an object containing a list of all the key-value pairs in the particular dictionary.

Syntax:

dict.items()

Python Dict Comprehension can be used to create a dictionary by accepting the key-value pairs from a particular iterable.

Syntax:

{key: value for key, value in iterable}

In the context of the deletion of key-value pairs from a dictionary, the items() method can be used to provide the list of key-value pairs to the dict comprehension as an iterable.

The if statement is used to encounter key-value mentioned ahead of it. If the mentioned key value is encountered, it returns a new dict containing all the key-value pairs excluding the key-value pair associated with the key to be deleted.

Example:

inp_dict = {"A":"Set","B":"Dict","C":"Tuple","D":"List",
             "1":"Java","2":"Fortan"}
print("Elements of the dict before performing the deletion operation:\n")
print(str(inp_dict))

res_dict = {key:value for key, value in inp_dict.items() if key != "1"} 


print("\nElements of the dict after performing the deletion operation:\n")
print(str(res_dict))

Output:

Elements of the dict before performing the deletion operation:

{'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}

Elements of the dict after performing the deletion operation:

{'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '2': 'Fortan'}

Delete a Dictionary in Python By Specifying Elements While Iteration

While dealing with Python Dictionary, we may come across situations wherein we would want a key-value pair to be deleted during the iteration of the dictionary.

To serve the purpose, we can create a list of the input-dictionary and use a for loop to traverse through the list of the dictionary.

Syntax:

list(dict)

Finally, by using an if statement, we would check for the loop to encounter the key to be deleted. As soon as the key is encountered, del keyword can be used to delete the key-value pair.

Example:

inp_dict = {"A":"Set","B":"Dict","C":"Tuple","D":"List",
             "1":"Java","2":"Fortan"}
print("Elements of the dict before performing the deletion operation:\n")
print(str(inp_dict))

for KEY in list(inp_dict): 
    if KEY =="B":  
        del inp_dict[KEY] 


print("\nElements of the dict after performing the deletion operation:\n")
print(str(inp_dict))

Output:

Elements of the dict before performing the deletion operation:

{'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}

Elements of the dict after performing the deletion operation:

{'A': 'Set', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}

Conclusion

Thus, we have unveiled the different techniques to delete a key-value pair from Python Dictionary.


References