Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading