Python Programming - Variables - Discussion

Discussion Forum : Variables - General Questions (Q.No. 33)
33.
Which of the following is a valid way to delete a key-value pair from a dictionary?
my_dict.delete("key")
del my_dict["key"]
my_dict.del("key")
All of the above are valid
Answer: Option
Explanation:

The del keyword can be used to remove a key-value pair from a dictionary. To delete the pair with key "key", you can use the syntax del my_dict["key"].

Other methods for removing key-value pairs from a dictionary include using the pop() method or the clear() method.

1. Using the pop() method:

my_dict.pop("key")

This method removes the key and returns its value. If the key is not found, a specified default value is returned, or a KeyError is raised.

2. Using the clear() method:

my_dict = {"a": 1, "b": 2, "c": 3}
my_dict.clear()
print(my_dict)  # Output: {}

It does not delete individual key-value pairs, but rather empties the entire dictionary.

Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.