del dictionary Python | Example code

The del keyword is used to delete the whole dictionary or specific element form 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:

del dictionary Python

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 and suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.