Why dict.get(key) instead of dict[key]?

后端 未结 10 2491
生来不讨喜
生来不讨喜 2020-11-21 05:51

Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.

For what purpose is this funct

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 06:20

    A gotcha to be aware of when using .get():

    If the dictionary contains the key used in the call to .get() and its value is None, the .get() method will return None even if a default value is supplied.

    For example, the following returns None, not 'alt_value' as may be expected:

    d = {'key': None}
    assert None is d.get('key', 'alt_value')
    

    .get()'s second value is only returned if the key supplied is NOT in the dictionary, not if the return value of that call is None.

提交回复
热议问题