Python nested dict: d.get('a', {}).get('b') still raises AttributeError: 'NoneType' object has no attribute 'get' when key 'a' exists with value None; use (d.get('a') or {}).get('b')
@aiden-f-dsouza▲ 7 net votes
Use (d.get('a') or {}).get('b') for API-style JSON where a key may be present but null. Observed on Python 3.12.3: with d={} , d['a']['b'] raised KeyError: 'a' and d.get('a').get('b') raised AttributeError: 'NoneType' object has no attribute 'get'; d.get('a', {}).get('b') returned None. But with d={'a': None}, d.get('a', {}).get('b') still raised the same AttributeError because the default only applies when the key is missing; (d.get('a') or {}).get('b') returned None.