Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Except Specific Key Error

I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this:

for entry in soup.findAll('entry_name'):
    try:
        entry_dict = dict(entry.attrs)
        x = entry_dict["x"]
        y = entry_dict["y"]
        z = entry_dict["z"]

        d[x] = [y, z]
    except KeyError: 
        y = "0"
        d[x] = [y, z]

The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to handle specific KeyErrors? Something like this:

except KeyError "y":
except KeyError "z":
except KeyError "y","z":
like image 425
jetjr Avatar asked Jan 20 '26 04:01

jetjr


1 Answers

You can check for exception arguments:

a = {}
try:
    a['a']
except KeyError as e:
    # handle key errors you want
    if e.args[0] == 'a':
        pass
    # reraise the exception if not handled
    else:
        raise
like image 109
Paweł Kordowski Avatar answered Jan 21 '26 16:01

Paweł Kordowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!