Make nested dictionary, unflatten
<p>I have a list of lists containing key and value like so:</p>

<pre><code>[
  ['mounts:device', '/dev/sda3'],
  ['mounts:fstype:[0]', 'ext1'],
  ['mounts:fstype:[1]', 'ext3']
]
</code></pre>

<p>Well I can easily change the list to this  </p>

<h1>(Lists arent seperated by ':')</h1>

<pre><code>[
  ['mounts:device', '/dev/sda3'],
  ['mounts:fstype[0]', 'ext1'],
  ['mounts:fstype[1]', 'ext3']
]
</code></pre>

<p>Whatever suits better for this problem:<br>
Problem is to create a dictionary:</p>

<pre><code>{
'mounts': {
    'device': '/dev/sda3',
    'fstype': [
        'ext1',
        'ext3'
    ]
}
</code></pre>

<p>It should also be possible to have lists in lists for example:</p>

<pre><code>['mounts:test:lala:fstype[0][0]', 'abc']
</code></pre>

<p>or</p>

<pre><code>['mounts:test:lala:fstype:[0]:[0]', 'abc']
</code></pre>

<p>This is what I have so far:</p>

<pre><code>def unflatten(pair_list):
    root = {}
    for pair in pair_list:
        context = root
        key_list = pair[0].split(':')
        key_list_last_item = key_list.pop()
        for key in key_list:
            if key not in context:
                context[key] = {}
            context = context[key]
        context[key_list_last_item] = pair[1]
    return root
</code></pre>

<p>Based on this answer <a href="http://stackoverflow.com/a/18648007/5413035">http://stackoverflow.com/a/18648007/5413035</a> but as requested I need recursivness and lists in the mix  </p>

<p>Thanks in advance</p>

<pre><code>input1=[
  ['mounts:device', '/dev/sda3'],
  ['mounts:fstype:[0]', 'ext1'],
  ['mounts:fstype:[1]', 'ext3']
]
input2={x[1]:x[0].split(':')[1] for x in input1}
input3=['ext3', 'ext1', '/dev/sda3']
input4=['fstype', 'fstype', 'device']
res={}
for x,y in zip(input3, input4):
    res.setdefault(y,[]).append(x)
res1=res.keys()
res2=res.values()
res3=[x[0] for x in res2 if len(x)==1]+[x for x in res2 if len(x)&gt;1]
result=dict(zip(res1,res3))

print result
</code></pre>

<p>Output :</p>

<pre><code>{'device': '/dev/sda3', 'fstype': ['ext3', 'ext1']}
</code></pre>

python python-3.x dictionary