您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

可作为dict.get的默认参数调用,如果键存在则不调用它

可作为dict.get的默认参数调用,如果键存在则不调用它

请参阅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显示了一种子类化方法defaultdictdict在某些情况下,您也可以只子类化:

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之一。

其他 2022/1/1 18:48:33 有468人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶