Access dict key and return None if doesn't exist

前端 未结 7 1312
生来不讨喜
生来不讨喜 2021-02-02 05:41

In Python what is the most efficient way to do this:

my_var = some_var[\'my_key\'] | None

ie. assign some_var[\'my_key\'] to

7条回答
  •  执笔经年
    2021-02-02 06:15

    You are looking for the get() method of dict.

    my_var = some_var.get('some_key')
    

    The get() method will return the value associated with 'some_key', if such a value exists. If the key is not present, then None will be returned.

提交回复
热议问题