recursively iterate nested python dictionary
<p>I have nested python dictionary like this.</p>

<pre><code>d = {}
d[a] = b
d[c] = {1:2, 2:3}
</code></pre>

<p>I am trying to recursively convert the nested dictionary into an xml format since there can be more nested dictionary inside such as <code>d[e] = {1:{2:3}, 3:4}</code>. My desired XML format is like this</p>

<pre><code>&lt;root&gt;
  &lt;a&gt;b&lt;/a&gt;
  &lt;c&gt;
    &lt;1&gt;2&lt;/1&gt; 
    &lt;2&gt;3&lt;/3&gt;
  &lt;/c&gt; 
&lt;/root&gt;
</code></pre>

<p>I have so far this python code to handle nested xml using lxml library. But it doesn't give me the desired output. </p>

<pre><code>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)
</code></pre>

<p>Any help is appreciated. Thank you. </p>

<p>The way you recall encode does not look correct. Maybe this helps. For simplicity I just append stuff to a list (called <code>l</code>). Instead, you should do your <code>etree.SubElement(...)</code>.</p>

<pre><code>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])
</code></pre>

python xml dictionary recursion lxml