请参阅dict.get()方法的答案和注释中的讨论返回指针。您必须将其分为两个步骤。
您的选择是:
defaultdict
如果您 始终 希望将该值用作默认值,并希望将其存储在中,请在可调用项中使用dict
。
使用条件表达式:
item = test['store'] if 'store' in test else run()
使用try
/ except
:
try:
item = test['store']
except KeyError: item = run()
用途get
:
item = test.get('store')
if item is None: item = run()
以及这些主题的变化。
glglgl显示了一种子类化方法defaultdict
,dict
在某些情况下,您也可以只子类化:
def run():
print "RUNNING"
return 1
class dict_nokeyerror(dict):
def __missing__(self, key):
return run()
test = dict_nokeyerror()
print test['a']
# RUNNING
# 1
仅当您 始终 希望dict
具有某些非标准行为时,子类化才有意义。如果您通常希望它表现得像个正常人,dict
并且只想get
在一个地方偷懒,请使用我的方法2-4之一。