1

I am currently doing something like this to access an array in my json object

teacher_topical_array = teacher_obj["medication"]["topical"]

However before doing that I would like to make sure the path teacher_obj["medication"]["topical"] exists and I am looking for a simpler approach to accomplish this.

Now I understand I could do something like this

if "medication" in teacher_obj:
    if "topical" in teacher_obj["medication"]:
             #yes the key exists

I wanted to know if I could accomplish the above in a different way. That might be more effective if I had to check for something like

teacher_obj["medication"]["topical"]["anotherkey"]["someOtherKey"]
martineau
  • 119,623
  • 25
  • 170
  • 301
James Franco
  • 4,516
  • 10
  • 38
  • 80
  • You can use exception handling `try: teacher_obj["medication"]["topical"]["anotherkey"]["someOtherKey"] except KeyError: ...`. – DYZ Aug 03 '17 at 00:32
  • @SnakesandCoffee Woah. The linked dupe has a similar answer to mine. – cs95 Aug 03 '17 at 00:33

1 Answers1

7

The LYBL approach: Chain get calls, if you don't want to use try-except braces...

teacher_topical_array = teacher_obj.get("medication", {}).get("topical", None)

The EAFP approach: Use a try-except block and catch a KeyError.

try:
    teacher_topical_array = teacher_obj["medication"]["topical"]
except KeyError:
    teacher_topical_array = []
cs95
  • 379,657
  • 97
  • 704
  • 746