Python Program - Delete an Element From a Dictionary

ht‮pt‬s://www.theitroad.com

here's a Python program that deletes an element from a dictionary:

# define a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 4}

# get the key to be deleted from user
key = input("Enter the key to be deleted: ")

# check if key is present in the dictionary
if key in my_dict:
    del my_dict[key]
    print(key, "deleted from the dictionary.")
else:
    print(key, "not found in the dictionary.")

# print the updated dictionary
print("Updated dictionary:", my_dict)

In this program, we first define a dictionary called my_dict with some key-value pairs.

We then use the input() function to get the key to be deleted from the user, and store it in the variable key.

We then check if the key is present in the dictionary using the in operator. If it is, we use the del keyword to delete the key-value pair from the dictionary. We also print out a message indicating that the key was deleted. If the key is not present in the dictionary, we print out a message indicating that it was not found.

Finally, we use the print() function to print out the updated dictionary. Note that the key-value pair corresponding to the deleted key will be missing from the updated dictionary.