Q: Python 3: Testing presence of each (sub)key in nested dict vs just using a try block? Poor practise or OK? May I ask: is the try block 2nd option considered poor practice? And if so, is there a more succinct way of testing a nested dict before referencing a sub key that may or may not exist?
Coming to python from perl...
Thank you :)
b = None
# a['x'] = {}
# a['x']['y'] = Wibble
if 'x' in a and 'y' in a['x']:
  b = a['x']['y']
if b is not None:
  # Do stuff with b

vs
b = None
try:
  b = a['x']['y']
except:
  pass
if b is not None:
  # Do stuff with b


A: try this
> b=a.get("x",{}).get("y")
  if b:
    #Do stuff with b


A: I'd go for the new walrus operator in 3.8:
a = { 'b': { 'c': 1, 'd': 2 }, 'e': {} }

if (b := a.get('b')) and (c := b.get('c')):
   print(c)

so if b is not present a.get('b') will return None and the and condition would return False.

A: Yes its even recommended as a common coding style: It is easier to ask for forgiveness than permission.
The only thing I would change is to not catch all exceptions, but just KeyError. And also I would use the else case to do the processing, instead of the None test.
try:
  b = a['x']['y']
except KeyError:
  pass
else:
  # do stuff with b

