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
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
.