Python getattr equivalent for dictionaries?

后端 未结 2 771
梦毁少年i
梦毁少年i 2021-02-02 05:55

What\'s the most succinct way of saying, in Python, \"Give me dict[\'foo\'] if it exists, and if not, give me this other value bar\"? If I were using a

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 06:12

    Also take a look at collections module's defaultdict class. It's a dict for which you can specify what it must return when the key is not found. With it you can do things like:

    class MyDefaultObj:
        def __init__(self):
            self.a = 1
    
    from collections import defaultdict
    d = defaultdict(MyDefaultObj)
    i = d['NonExistentKey']
    type(i)
    
    

    which allows you to use the familiar d[i] convention.

    However, as mikej said, .get() also works, but here is the form closer to your JavaScript example:

    d = {}
    i = d.get('NonExistentKey') or MyDefaultObj()
    # the reason this is slightly better than d.get('NonExistent', MyDefaultObj())
    # is that instantiation of default value happens only when 'NonExistent' does not exist.
    # With d.get('NonExistent', MyDefaultObj()) you spin up a default every time you .get()
    type(i)
    
    

提交回复
热议问题