Python覆盖列表值

时间:2018-07-24 16:58:29

标签: python list dictionary

我正在尝试解析一些XML文件。但是由于某种原因,它甚至覆盖了我添加到列表中的值。

此处的代码:

def parseXML():
    xmlfiles = glob.glob('./*.xml')
    temp = {}

    for host in xmlfiles:
        tree = ET.parse(host)
        root = tree.getroot()

        for wizard in tree.findall('.'):
            for grandpa in wizard:
                for parent in grandpa:
                    if parent.get('addr') != None:
                        ip = parent.get('addr')
                        temp[ip] = {}
                    for child in parent:
                        if child.get('portid') != None:
                            for grandchild in child:
                                if grandchild.get('name') != None:
                                    name = grandchild.get('name')
                                    if child.get('portid') not in temp:
                                        temp[ip][name] = []
                                        temp[ip][name].append(child.get('portid'))
                                    else:
                                        print (temp + " else")


    print (temp)

预期结果:

{'127.0.0.2': {'ssh': ['22'], 'http': ['80','8080']}, '127.0.0.1': {'ssh': ['22'], 'http': ['80','8080']}}

但是我却得到了:

{'127.0.0.2': {'ssh': ['22'], 'http': ['8080']}, '127.0.0.1': {'ssh': ['22'], 'http': ['8080']}}

1 个答案:

答案 0 :(得分:1)

temp[ip][name] = []
temp[ip][name].append(child.get('portid'))

您要在每次追加之前清除列表。尝试将第一行移动到当前所在的if块上方。