Access dict key and return None if doesn't exist

前端 未结 7 1438
生来不讨喜
生来不讨喜 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:19

    try:
        my_var = some_var
    except:
        my_var = None
    

    But honestly this probably doesn't get to the heart of what you're trying to do... We need more context to more fully answer.

提交回复
热议问题