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
>Solution :
try this
> b=a.get("x",{}).get("y")
if b:
#Do stuff with b