Wil*_*ill 11 python dictionary lazy-evaluation
如果该值尚未设置,那么在a中设置值的最pythonic方法dict是什么?
目前我的代码使用if语句:
if "timeout" not in connection_settings:
connection_settings["timeout"] = compute_default_timeout(connection_settings)
Run Code Online (Sandbox Code Playgroud)
dict.get(key,default)适用于使用dict的代码,而不适用于准备将dict传递给另一个函数的代码.你可以用它来设置一些东西,但它不是更漂亮的imo:
connection_settings["timeout"] = connection_settings.get("timeout", \
compute_default_timeout(connection_settings))
Run Code Online (Sandbox Code Playgroud)
即使dict包含密钥,也会评估计算功能; 错误.
Defaultdict是默认值相同的时候.
当然,有很多时候你设置了不需要计算作为默认值的主要值,它们当然可以使用dict.setdefault.但是更复杂的情况呢?
Jan*_*ila 26
dict.setdefault将精确地"仅在没有设置值的情况下在字典中设置值",这是你的问题.但是,您仍然需要计算值以将其作为参数传递,这不是您想要的.
wim*_*wim 10
这是一个非答案,但我会说最pythonic是if语句,因为你有它.你用__setitem__其他方法抵制了对单行的冲动.您已经避免了逻辑中可能存在的错误,因为在尝试通过短路and/ or黑客攻击时可能会出现现有但错误的值.很明显,在没有必要时不使用计算功能.
它清晰,简洁,可读 - pythonic.
一种方法是:
if key not in dict:
dict[key] = value
Run Code Online (Sandbox Code Playgroud)
从Python 3.9开始,您可以使用合并运算符 |来合并两个字典。右侧的指令优先:
d = { key: value } | d
Run Code Online (Sandbox Code Playgroud)
注意:这将创建一个包含更新值的新字典。