Nested list into a hierarchical dict
<p>I have a nested list that I need to convert into a hierarchical dictionary. However I am a bit confused how to achieve it in a clean pythonic way. Here's a somewhat ugly sample code that I have come up with. How to improve it?</p>

<pre><code>from itertools import tee,izip
import json

L=[(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)]

def pairs(iterable):
    a,b = tee(iterable)
    b.next()
    return izip(a,b)

def innerfunc(pairs,d):
    try:
        pair           = pairs.next()
        item, nextitem = pair        
    except StopIteration:       
        return 
    if item in d:        
        innerfunc(pairs,d[item])
    else:        
        d[item]= {}
        {nextitem : innerfunc(pairs,d[item])}


def outerfunc(matrix):
    result_dict={}
    for row in matrix:        
        iter_pairs = pairs(row+(0,))
        innerfunc(iter_pairs,result_dict)
    return result_dict

print json.dumps(outerfunc(L), sort_keys=True, indent=4)
</code></pre>

<p>Output:</p>

<pre><code>{
    "1": {
        "2": {
            "3": {
                "4": {
                    "5": {}
                }
            }, 
            "7": {}
        }
    }, 
    "2": {
        "3": {
            "5": {}
        }
    }, 
    "3": {
        "4": {
            "5": {
                "6": {}
            }
        }
    }
}
</code></pre>
