MathGirl
MathGirl

Reputation: 75

check whether an element have attribute or not python3

I am using python3.4 and parsing an xml file by etree. some of the node have attribute "meaning" and some of them have attribute "role" and some have both. these nodes may have other attributes but not important to me. I need to extract these attributes (meaning and role) if they are exist. if it is there I used:

role = XMTok.attrib["role"]

but if the node dose not have attribute "role" then it give me this error:

KeyError: 'role'

is there a way to check first if the node have attribute "role" or not, if yes then extract it and if no then continue?

Upvotes: 0

Views: 72

Answers (2)

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

Use __dict__ to check the attribute. so XMTok.attrib._dict__ will help.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121186

attrib is a standard dictionary, so you can use the in membership operator to test:

if 'role' in XMTok.attrib:

or you can use dict.get() and have a default returned if the key is missing (None by default, or you can specify something else):

role = XMTok.attrib.get('role', 'No role set')

Upvotes: 3

Related Questions