gpt4 book ai didi

python - 当它的键未知时从字典中删除一个项目

转载 作者:IT老高 更新时间:2023-10-28 21:06:21 27 4
gpt4 key购买 nike

按值从字典中删除项目的最佳方法是什么,即当项目的键未知时?这是一个简单的方法:

for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]

有没有更好的方法?迭代时从字典中变异(删除项目)有什么问题吗?

最佳答案

dict.pop(key[, default]) 方法允许您在知道 key 时删除项目。如果删除项目,则返回键处的值,否则返回作为 default 传递的内容。见 the docs .'

例子:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}

关于python - 当它的键未知时从字典中删除一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5447494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com