The del keyword is used to delete the whole dictionary or specific element from a dictionary in Python. Python del
is actually a keyword that is basically used for the deletion of objects.
Example del dictionary Python
Simple example code deletes dictionary object.
a_dict = {"One": 1, "Two": 2, "Three": 3}
del a_dict
print(a_dict)
Output:
Code del item from dictionary Python
This way you can delete a single key-value pair from the dictionary.
del d[key]
Example code to remove an element from the dictionary using his value python.
a_dict = {"One": 1, "Two": 2, "Three": 3}
desired_value = 2
for key, value in a_dict.items():
if value == desired_value:
del a_dict[key]
break
print(a_dict)
Output: {‘One’: 1, ‘Three’: 3}
Do comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.