【发布时间】:2022-11-03 20:31:38
【问题描述】:
我对以下行为感到有些困惑。我正在从字典中检索值,这样如果一个键不存在,我会调用一个函数来创建该值并将其插入到字典中。我通过dictionary.get 方法的default 参数来做到这一点。问题是即使值已经存在于字典中,默认函数也会被调用。
真是令人难以置信。关于为什么会发生这种情况的任何想法?
dictionary = {}
def load_default(key):
print("Inside function")
value = "world"
dictionary[key] = value
return value
print(dictionary)
'{}' #empty dict, everything ok
value = dictionary.get("hello", load_default("hello"))
'Inside function' # we ask for "hello", which does not exist so we call load_default
print(dictionary)
"{'hello': 'world'}" # the dict now contains de key "hello"
value = dictionary.get("hello", load_default("hello"))
'Inside function' # we ask for "hello" again, but load_default is called instead ("Inside function" is printed) I would expect the dict to return only the value and not call `load_default`
在给定的示例中,我希望字典返回值 world 而不调用 load_default 函数
【问题讨论】:
标签: python dictionary