Search code examples
pythondictionarygraph

How to transform a list of lists in Python into a dictionary


I have in Python an structure like this one

example = {
    ['g': 'h'],
    [
        {'a':'b'}, {'c': 'd'},
        {'a':'b'}, {'e', 'f'}
     ]
}

I want to create a dictionary that represents the information of this list considering it a graph in the sense that the info goes from left to right

The output I want, for the example above is:

output = {
{'a': 
    {'b': 
            {'c': 'd'},
            {'e', 'f'}
     }
     ,
    {'g': 'h'}
}

Solution

  • If you used a set of functions like

    def kvCombine(obj:list):
        if isinstance(obj, dict): obj = list(obj.items()) 
        if not isinstance(obj, list): return obj
        obj = [t for lt in [
            list(o.items()) if isinstance(o,dict) else [o] for o in obj
        ] for t in lt]
        
        if not all(isinstance(t, tuple) and len(t)==2 for t in obj): return obj
        kList = set(k for k, v in obj)
        kvPairs = [(ki, [v for k, v in obj if k==ki]) for ki in kList]
        return {k: v[0] if len(v)==1 else kvCombine(v) for k, v in kvPairs}
    
    def dict_graph(pList):
        if not isinstance(pList, list): return pList
        if not pList: return None # {} # []
        if len(pList)==1: return dict_graph(pList[0])
    
        if any(isinstance(p, list) for p in pList):
            return kvCombine([  (p,None) if not isinstance(p,list) else 
                                (p[0],dict_graph(p[1:])) for p in pList if p!=[] ])
        
        if len(pList)==2: return {pList[0]: pList[1]}
        return {pList[0]: dict_graph(pList[1:])}
    

    then with a list of lists:

    example = [[ 'a', 'b', 'c', 'd'], [ 'a', 'b', 'e', 'f'], [ 'g', 'h']]
    example_graph = dict_graph(example)
    

    example_graph would look like

    {'a': {'b': {'c': 'd', 'e': 'f'}}, 'g': 'h'}
    
    {
        "a": {
            "b": {
                "c": "d",
                "e": "f"
            }
        },
        "g": "h"
    }