向嵌套字典添加值时出错 (python)

Error adding values to nested dictionary (python)

我一直在研究解析一些 XML 数据并将特定值放入嵌套字典中。查看数据并研究如何最好地解析数据后,我决定 XPath 解析比子对象解析更合适,因为它的结构不适合子解析。

所以我希望将这些数据移动到嵌套字典中以便稍后输出。我第一次尝试添加一个值似乎成功了,但当它到达第一个内部项目时,我收到了一个错误。我想我正确地理解了这个错误,我知道 python 中的字符串是不可变的,但我不明白为什么它在第一个键上有效而在第二个键上失败。任何人都可以解释或指向某个地方吗?

我收到的错误如下:TypeError: 'str' object does not support item assignment 这是在下一行 dictionary['host']['port'] = port。如前所述,这种方法似乎适用于这一行 dictionary['host'] = host我还想指出,我不是 100% 确定这种方法可行,我目前正在考虑实现我的目标的想法。

from xml.etree import ElementTree

data_file = 'data.xml'

dictionary = {}
dictionary['host'] = {}
dictionary['host']['port'] = {}
dictionary['host']['port']['service'] = {}


with open(data_file, 'rt') as f:
    tree = ElementTree.parse(f)

for node in tree.findall('.//address'):
    if (node.attrib.get('addrtype') == 'ipv4'):
        host = node.attrib.get('addr')
        dictionary['host'] = host
        for node in tree.findall('.//port'):
            port = node.attrib.get('portid')
            dictionary['host']['port'] = port
            for node in tree.findall('.//service'):
                product = node.attrib.get('product')
                dictionary['host']['port']['service'] = product

问题

dictionary['host']['port'] = port 本身没有任何问题,但问题出现是因为您在相关行之前更改了 dictionary['host'] 的值。

host = node.attrib.get ('addr')
dictionary['host'] = host # <- here

Note: After that point, dictionary['host'] no longer refers to a (nested) dict, because the key has been overwritten with an object of type str. The object of type str is the indirect result of node.attrib.get('addr').


下面的测试用例很容易重现该问题:

>>> x = {}
>>> x['host'] = "some string"
>>> x['host']['port'] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment