仅在尚未设置值的情况下在dict中设置值

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将精确地"仅在没有设置值的情况下在字典中设置值",这是你的问题.但是,您仍然需要计算值以将其作为参数传递,这不是您想要的.

  • 对于未来的googlers:这可能不是问题提供者想要的答案,但它是你想要的答案. (9认同)
  • `dict.setdefault()` 设计用于当您有效地*获取密钥的值*时使用,您希望确保密钥始终存在。将其用作 setter 只会与正常使用背道而驰。使用 `if key not in dictionary: dictionary[key] = compute_default_timeout(:..)` 更加清晰和直接。此外,OP 特别要求一个选项,在需要之前不计算新值,**这是你不能用 `dict.setdefault()` 做的。** (2认同)

wim*_*wim 10

这是一个非答案,但我会说最pythonic是if语句,因为你有它.你用__setitem__其他方法抵制了对单行的冲动.您已经避免了逻辑中可能存在的错误,因为在尝试通过短路and/ or黑客攻击时可能会出现现有但错误的值.很明显,在没有必要时不使用计算功能.

它清晰,简洁,可读 - pythonic.


kas*_*sky 6

一种方法是:

if key not in dict:
  dict[key] = value
Run Code Online (Sandbox Code Playgroud)

  • @slaughter98:但这并不能使 `dict.setdefault()` 成为正确的选择,因为它不是 `dict.setdefault()` 唯一做的事情。 (2认同)

Rot*_*eti 5

Python 3.9开始,您可以使用合并运算符 |来合并两个字典。右侧的指令优先:

d = { key: value } | d
Run Code Online (Sandbox Code Playgroud)

注意:这将创建一个包含更新值的新字典。