[英]recursively iterate nested python dictionary
I have nested python dictionary like this. 我已经像这样嵌套了python字典。
d = {}
d[a] = b
d[c] = {1:2, 2:3}
I am trying to recursively convert the nested dictionary into an xml format since there can be more nested dictionary inside such as d[e] = {1:{2:3}, 3:4}
. 我试图将嵌套的字典递归转换为xml格式,因为里面可以有更多的嵌套字典,例如
d[e] = {1:{2:3}, 3:4}
。 My desired XML format is like this 我想要的XML格式是这样的
<root>
<a>b</a>
<c>
<1>2</1>
<2>3</3>
</c>
</root>
I have so far this python code to handle nested xml using lxml library. 到目前为止,我已经使用python代码使用lxml库处理嵌套的xml。 But it doesn't give me the desired output.
但这没有给我想要的输出。
def encode(node, Dict):
if len(Dict) == 0:
return node
for kee, val in Dict.items():
subNode = etree.SubElement(node, kee)
del msgDict[kee]
if not isinstance(val, dict):
subNode.text = str(val)
else:
return encode(subNode, val)
Any help is appreciated. 任何帮助表示赞赏。 Thank you.
谢谢。
The way you recall encode does not look correct. 您回忆编码的方式看起来不正确。 Maybe this helps.
也许这会有所帮助。 For simplicity I just append stuff to a list (called
l
). 为了简单起见,我只将内容添加到列表(称为
l
)中。 Instead, you should do your etree.SubElement(...)
. 相反,您应该执行
etree.SubElement(...)
。
def encode(D, l=[]):
for k, v in D.items():
if isinstance(v, dict):
l2 = [k]
encode(v, l2)
l.append(l2)
else:
l.append([k, v])
I found the bug in my code, which is I didn't return the recursive call back to the original loop. 我在代码中找到了错误,这是我没有将递归调用返回到原始循环。 After going inside nested elements, it "returns" and doesn't get back to original loop.
进入嵌套元素后,它会“返回”,并且不会回到原始循环。 Instead of
return encode(subNode, val)
, saving in a variable element = encode(subNode, val)
solves the problem. 代替
return encode(subNode, val)
,保存一个变量element = encode(subNode, val)
可以解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.