Python Program to Delete an Element From a Dictionary


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In programming, deleting an element refers to the process of removing an item from a data structure such as a list, array, or dictionary. Depending on the programming language and the data structure used, there are different ways to delete an element.


Python Code :

The Below Python program deletes a key-value pair from a dictionary based on the key:


# Define the dictionary and the key to delete
my_dict = {"apple": 3, "banana": 2, "orange": 1}
key_to_delete = "banana"

# Use the del keyword to delete the key-value pair
del my_dict[key_to_delete]

# Print the dictionary to confirm that the key-value pair was deleted
print(my_dict)

In this program, we first define the dictionary that we want to delete the key-value pair from by assigning it to the variable my_dict. We also define the key that we want to delete by assigning it to the variable key_to_delete.

We then use the del keyword followed by the dictionary name and the key to delete to remove the key-value pair from the dictionary.

Finally, we print the dictionary to confirm that the key-value pair was deleted. Note that if the key does not exist in the dictionary, a KeyError exception will be raised. To avoid this, you can use the pop() method instead, which removes the key-value pair if it exists and returns the corresponding value. If the key does not exist, the pop() method returns a default value that you can specify as the second argument to the method.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co