【问题标题】:Python: Local variable reference before assignment [duplicate]Python:赋值前的局部变量引用[重复]
【发布时间】:2017-08-18 03:56:52
【问题描述】:

我正在尝试使用 Elementree 将 XML 文件转换为 Dictionary。 XML 文件中有各种标签,但对于每条记录,ID 标签都是主键。因此,我尝试创建的字典将父标记作为 ID,将所有其他属性作为其子键。但是我收到一个 unboundlocalerror 说'局部变量 x 在赋值之前是引用。代码如下:

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)

【问题讨论】:

标签: python xml


【解决方案1】:

这不起作用,您必须使用 root 值或 condition 初始化 x,然后等到找到第一个 subchild
您还分配了 x = test_dict 而没有 ()

带有条件的例子,例如:

...
temp_dict={}
x = None
def create_dict():
    ...
        if subchild.tag=='ID':
            x = test_dict
    ...
        if x:
            temp_dict[x]=test_dict

...

【讨论】:

  • 是的..我明白了!谢谢@stovfl
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-28
  • 1970-01-01
  • 2015-06-14
  • 2018-06-29
  • 1970-01-01
相关资源
最近更新 更多