如果 dict 中的键不存在,Python 会更新它

标签 python dictionary

如果键不在 dict.keys() 中,我想在 dict 中插入一个键值对。 基本上我可以这样做:

if key not in d.keys():
    d[key] = value

但是有更好的方法吗?或者这个问题的pythonic解决方案是什么?

最佳答案

你不需要调用d.keys(),所以

if key not in d:
    d[key] = value

就够了。没有比这更清晰、更易读的方法了。

您可以使用 dict.get() 再次更新,如果键已经存在,它将返回一个现有值:

d[key] = d.get(key, value)

但我强烈建议不要这样做;这是代码打高尔夫球,妨碍维护和可读性。

关于如果 dict 中的键不存在,Python 会更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315072/

相关文章:

python - tkinter gui 已关闭但控制台未关闭

python - 从 Python 字典中插入值,包括 MySQL 的键

python - 根据字符串拆分将列表拆分为子列表

python - tensorflow 中的剪切图像

python - 在代码更改时自动重新加载 python Flask 应用程序

python - tokyo-python 安装问题

c++ - 在 map 中传递三个参数显示错误

python - 如何永久修改python中的字典?

python - 字典到python中的字典

python - 使用 Python 向 ASPX 页面提交请求时出错