📜  python delete dict key if exists - Python (1)

📅  最后修改于: 2023-12-03 14:45:57.283000             🧑  作者: Mango

Python - Delete Dictionary Key if Exists

In Python, you can delete a key-value pair from a dictionary using the del keyword. To ensure the key exists before deleting it, you can use the in operator to check if the key is present in the dictionary.

Here is an example of deleting a key from a dictionary if it exists:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

if "key2" in my_dict:
    del my_dict["key2"]

print(my_dict)

Output:

{"key1": "value1", "key3": "value3"}

In this example, the del statement deletes the key "key2" from the dictionary my_dict if it exists. Otherwise, it does nothing. The print statement is used to display the modified dictionary after deleting the key.

You can modify the code to delete a key from any dictionary by replacing "key2" with the desired key.

Note that if you try to delete a key that does not exist in the dictionary, it will raise a KeyError. To avoid this, you can use a try-except block to handle the exception, as shown in the following example:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

try:
    del my_dict["key4"]
except KeyError:
    pass

print(my_dict)

Output:

{"key1": "value1", "key2": "value2", "key3": "value3"}

In this example, the try-except block catches the KeyError raised when trying to delete the non-existent key "key4". The pass statement is used to do nothing and continue execution without raising an error.

Remember to be cautious when deleting keys from dictionaries as it modifies the original dictionary.