要从Python字典中删除一个键:
- 使用dict.pop()
- 使用 del 关键字
- 使用del和try/except从字典中删除键
如何在 Python 中从字典中删除键
Python dictionary pop() 是一个内置的方法,可以从 dictionary 中删除一个键。pop() 方法接受一个 key 参数并删除该键值元素。例如, dict pop() 方法从一个字典中删除并返回一个项目,提供给定的 key。
如果 key 存在于 dictionary 中,那么 dict.pop() 从 dictionary 中删除带有给定 key 的元素并返回其值。
如果给定的 key 不存在于 dictionary 中,它返回给定的 Default 值。如果给定的 key 不存在于 dictionary 中,并且 No Default 值被传递给 pop() ,它将抛出KeyError。
请看下面的代码:
# app.py
adict = {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
print(adict)
rEl = adict.pop('c')
print(adict)
print('Removed element: ', rEl)
输出
python3 app.py
{'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
{'a': 'abel', 'b': 'billie', 'd': 'delray'}
Removed element: cyrus
dict.pop() 方法返回被删除的元素。
使用 del 从 dictionary 中删除键
Python del 关键字用来从一个集合中删除一个或多个元素。Del 对列表和字典都有效。
请看下面的语法:
del d[key]
del 语句从 dictionary 中删除给定的项目。如果给定的键在字典中不存在,它将抛出KeyError。
请看下面的代码:
adict = {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
print(adict)
if "c" in adict:
del adict["c"]
print("Updated Dictionary :", adict)
输出
python3 app.py
{'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
Updated Dictionary : {'a': 'abel', 'b': 'billie', 'd': 'delray'}
del 是一个清晰而快速的方法来从 dictionary 中删除元素。
使用 del 和 try/except 从 dictionary 中删除键
请看下面的代码:
# app.py
adict = {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
print(adict)
key = "e"
try:
del adict[key]
except KeyError:
print(f'Key {key} not found')
print("Updated Dictionary :", adict)
输出
python3 app.py
{'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
Key e not found
Updated Dictionary : {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
在上面的程序中,我们试图删除一个在字典中不存在的键,并捕捉到错误。
总结
在 Python 中,有不止一种标准的方法可以从 dictionary 中删除键。例如,你可以使用del,dict.pop()方法来删除一个元素。