pythondictionaryplottree

Python nested dictionary to Tree


I am trying to display my nested dictionary as a Tree.

data = {"L1" : 
            {"sub L1" : 
                "sub sub L1"}, 
        "L2" :
            "sub L2", 
        "L3" :
            {"sub L3" :
                {"sub sub L3" :
                    "sub sub sub L3"}}}

As you can see, it's all text data and there is no real correlation between any of it.

I have tried networkx and dendograms but they seem to be breaking as I have a nested dictionary.

Is there a better way to do this?


Solution

  • You can recursively traverse your dict and make a DiGraph from the collected edges :

    import networkx as nx
    
    def traverse(data, p="L0"):
        if isinstance(data, dict):
            for k, v in data.items():
                yield p, k
                yield from traverse(v, k)
        elif p is not None:
            yield p, data
    
    DG = nx.DiGraph(traverse(data)) # or `Graph` to remove the arrows
    
    # requires `pygraphviz`
    from IPython.display import Image
    Image(nx.nx_agraph.to_agraph(DG).draw(format="png", prog="dot"))
    

    enter image description here