Python:赋值前的局部变量引用 [英] Python: Local variable reference before assignment
问题描述
我正在尝试使用 Elementree 将 XML 文件转换为字典.XML 文件中有各种标签,但对于每条记录,ID 标签是主键.因此,我尝试创建的字典将父标记作为 ID,将所有其他属性作为其子键.但是我收到一个 unboundlocalerror 说'局部变量 x 是赋值前的引用.代码如下:
tree = ET.parse(xml_file)root = tree.getroot()temp_dict={}def create_dict():test_dict = {}对于 root.iter() 中的孩子:如果 subchild.tag=='ID':x=(child.text)别的:test_dict[subchild.tag]= subchild.texttemp_dict[x]=test_dict返回(temp_dict)
这行不通,你必须用 root 值或 初始化
并等待,直到找到第一个x
条件subchild
.
您还分配了 x = test_dict
而没有 ()
.
条件示例,例如:
<预><代码>...temp_dict={}x = 无def create_dict():...如果 subchild.tag=='ID':x = test_dict...如果 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
...
这篇关于Python:赋值前的局部变量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!