python - 将值添加到嵌套字典时出错(python)

标签 python dictionary elementtree

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

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

我收到的错误如下:TypeError:'str'对象不支持项目分配这位于以下行dictionary['host']['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

关于python - 将值添加到嵌套字典时出错(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32928879/

相关文章:

Python-存在多个同名元素属性时如何编辑特定的XML元素内容?

php - 从 php 调用时 python 输出无法正确输出

python - python包的数据缓存

python - 直接在线运行一个Jupyter notebook(不用本地下载)

javascript - 'this' 关键字在 map() 和 call() 中如何工作?

python - 我如何根据日期时间对这个字典进行排序?

ios - 如何在字典数组中的内部数组上应用过滤器?

python - 我可以禁用在 ElementTree XMLParser 中解析的实体吗?

python /元素树 : Parsing inline elements w/respect to surrounding text?

python - 使用 python 验证 SSL 中的对等体