Python Program to remove the key from a dictionary


April 2, 2022, Learn eTutorial
952

In this simple python program, we need to remove the key from a dictionary. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What is a dictionary in python?

In this basic python program on the dictionary, we need to remove a key from it. Dictionary is a set of elements that are arranged in a format like key and value pairs in unordered format. Dictionary is handy for retrieving the value if we know the key as every value is associated with a key. 

We can add the values into a dictionary using the braces, and each element in a python dictionary separated by a comma. In the dictionary, all the values must have a key. So we need to add the key-value pair format. Also, the key must be a string or tuple, or a number and be unique. In the case of the value, there are no such conditions as it can be anything or any format.

How to remove a key value from a python dictionary?

In this simple python program, we need to remove a key that is given by the user. For that, we initialize a predefined dictionary with some values and keys in that. Then we print the dictionary using the print function. Now we accept the key from the user, which we want to delete. Open an if condition to check for the key and delete the key if found using del function. Else we print the key is not present in the dictionary and exit the program. If we found the key, print the updated dictionary.

ALGORITHM

STEP 1: Initialize a predefined dictionary with a set of key-value pairs.

STEP 2: Print the Dictionary using the print function.

STEP 3: Accept the key value from the user, which we want to delete.

STEP 4: Use an if condition to check the key value is present in the dictionary,

STEP 5: If found, delete the key-value using del.

STEP 6: Else print the key not found and exit the program.

STEP 7: If the key value is found. Print the updated dictionary using python language.

Python Source Code

                                          d = {'a':1,'b':2,'c':3,'d':4}
print("dictionary before deletion")
print(d)
key=input("Enter key to delete:")
if key in d: 
    del d[key]
else:
    print("Cant able to found the key")
    exit(0)
print("Dictionary after deletion")
print(d)
                                      

OUTPUT

dictionary before deletion
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Enter the key to delete: c

Dictionary after deletion
{'a': 1, 'b': 2, 'd': 4}