Access dict key and return None if doesn't exist

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

    In python "|" is translated to "or", so:

    my_var = some_var or None
    

    Edit:

    You've edited your initial post. The correct way to do what you want is:

    my_var = some_var.get('my_key', None)
    

提交回复
热议问题