调用为dict.get的默认参数,如果键存在,则调用它 [英] Callable as the default argument to dict.get without it being called if the key exists

查看:74
本文介绍了调用为dict.get的默认参数,如果键存在,则调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图提供一个函数作为字典get函数的默认参数,像这样

I am trying to provide a function as the default argument for the dictionary's get function, like this

def run():
   print "RUNNING"

test = {'store':1}
test.get('store', run())

但是,当运行此操作时,它显示以下输出:

However, when this is run, it displays the following output:

RUNNING
   1

所以我的问题是,作为标题说,有没有办法提供一个可调用作为get方法的默认值,如果该键存在,则调用它?

so my question is, as the title says, is there a way to provide a callable as the default value for the get method without it being called if the key exists?

推荐答案

请参阅 dict.get( )方法返回一个指针。您必须将其分为两个步骤。

See the discussion in the answers and comments of dict.get() method returns a pointer. You have to break it into two steps.

您的选项是:


  1. 使用 defaultdict 与可调用,如果您始终希望将该值作为默认值,并将其存储在 dict

  1. Use a defaultdict with the callable if you always want that value as the default, and want to store it in the dict.

使用条件表达式:

item = test['store'] if 'store' in test else run()


  • 使用尝试 /

    try:
        item = test['store']
    except KeyError:
        item = run()
    


  • 使用获取

    item = test.get('store')
    if item is None:
        item = run()
    


  • 这些主题的变体。

    glglgl显示一种子类 defaultdict 的方法,您还可以在某些情况下子类 dict / p>

    glglgl shows a way to subclass defaultdict, you can also just subclass dict for some situations:

    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。

    Subclassing only really makes sense if you always want the dict to have some nonstandard behavior; if you generally want it to behave like a normal dict and just want a lazy get in one place, use one of my methods 2-4.

    这篇关于调用为dict.get的默认参数,如果键存在,则调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆