Is there a cleaner way to chain empty list checks in Python?

coding-style, python

Solution

try:
  bs = a["key"][0][0]
# Note: the syntax for catching exceptions is different in old versions
# of Python. Use whichever one of these lines is appropriate to your version.
except KeyError, IndexError, TypeError:   # Python 3
except (KeyError, IndexError, TypeError): # Python 2
  bs = []
for b in bs:

And you can package it up into a function, if you don't mind longer lines:

def maybe_list(f):
  try:
    return f()
  except KeyError, IndexError, TypeError:
    return []

for b in maybe_list(lambda: a["key"][0][0]):

Problem

I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this: ``` if a.get("key") and a["key"][0] and a["key"][0][0] : for b in a["key"][0][0] : #Do something ``` which works, but is pretty ugly. It seems there has to be a better way to do this, so what's a more elegant solution?

Original source