深度阅读

How to remove key from dictionary in Python

作者
作者
2023年08月22日
更新时间
13.49 分钟
阅读时间
0
阅读量

In Python, you can remove a key from a dictionary using the del statement or the pop() method. Here are some examples:

Using del:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
del my_dict["key2"]
print(my_dict)

In this example, the del statement is used to remove the key-value pair with key "key2" from the dictionary my_dict. The output will be 'key1': 'value1', 'key3': 'value3' (since the key-value pair with key "key2" has been deleted).

Using pop():

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
my_dict.pop("key2")
print(my_dict)

In this example, the pop() method is used to remove the key-value pair with key "key2" from the dictionary my_dict. The output will again be 'key1': 'value1', 'key3': 'value3'.

Note that if you try to remove a key that does not exist in the dictionary, both del and pop() will raise a KeyError. To avoid this, you can use the optional second argument of pop(), which specifies a default value to return if the key is not found:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
my_dict.pop("key4", None)  # will not raise an error

In this example, the pop() method is used with a default value of None, which will be returned if the key "key4" is not found in the dictionary.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。