Access dict key and return None if doesn't exist

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

    For a new dict:

    from collections import defaultdict
    # None is the default, but you can change this default value
    d = defaultdict(lambda: None)
    

    For an existing dict:

    from collections import defaultdict
    # convert a dictionary to a defaultdict
    d = defaultdict(lambda: None,d)
    

提交回复
热议问题