Access dict key and return None if doesn't exist

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

    The great thing about the .get() method is you can actually define a value to return in case the key doesn't exist.

    my_dict = { 1: 'one', 2: 'two' }
    print my_dict.get(3, 'Undefined key')
    

    would print.

    Undefined key
    

    This is very helpful not only for debugging purposes, but also when parsing json (in my experience, at least), and you should prefer using get() over [] as much as possible.

提交回复
热议问题