0

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)
J.D
  • 45
  • 1
  • 6
  • I guess I was able to figure out this one. Can you help me on this one? https://stackoverflow.com/questions/45724345/python-unable-to-extract-attribute-using-xmltodict – J.D Aug 17 '17 at 12:04

1 Answers1

0

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

...
stovfl
  • 14,998
  • 7
  • 24
  • 51