Python: Local variable reference before assignment
Question:
I am trying to convert an XML file to Dictionary using Elementree. There are various tags in the XML file, but for every record, the ID tag is the primary key. So the dictionary I am trying to create has the parent tag as the ID and all other properties as its sub keys. But I am getting an unboundlocalerror saying that ‘local variable x is reference before assignment. Here is the code:
tree = ET.parse(xml_file)
root = tree.getroot()
temp_dict={}
def create_dict():
test_dict = {}
for child in root.iter():
if subchild.tag=='ID':
x=(child.text)
else:
test_dict[subchild.tag]= subchild.text
temp_dict[x]=test_dict
return ( temp_dict)
Answers:
This will not work, you have to init x
with a root Value or a condition
and wait until the First subchild
is found.
You have also assign x = test_dict
without ()
.
Example with Condition, for instance:
...
temp_dict={}
x = None
def create_dict():
...
if subchild.tag=='ID':
x = test_dict
...
if x:
temp_dict[x]=test_dict
...
I am trying to convert an XML file to Dictionary using Elementree. There are various tags in the XML file, but for every record, the ID tag is the primary key. So the dictionary I am trying to create has the parent tag as the ID and all other properties as its sub keys. But I am getting an unboundlocalerror saying that ‘local variable x is reference before assignment. Here is the code:
tree = ET.parse(xml_file)
root = tree.getroot()
temp_dict={}
def create_dict():
test_dict = {}
for child in root.iter():
if subchild.tag=='ID':
x=(child.text)
else:
test_dict[subchild.tag]= subchild.text
temp_dict[x]=test_dict
return ( temp_dict)
This will not work, you have to init x
with a root Value or a condition
and wait until the First subchild
is found.
You have also assign x = test_dict
without ()
.
Example with Condition, for instance:
...
temp_dict={}
x = None
def create_dict():
...
if subchild.tag=='ID':
x = test_dict
...
if x:
temp_dict[x]=test_dict
...