我一直在考虑解析一些 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 typestr
. The object of typestr
is the indirect result ofnode.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/