Python getattr equivalent for dictionaries?

后端 未结 2 772
梦毁少年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:28

    dict.get(key, default) returns dict[key] if key in dict, else returns default.

    Note that the default for default is None so if you say dict.get(key) and key is not in dict then this will just return None rather than raising a KeyError as happens when you use the [] key access notation.

提交回复
热议问题