Dictionary object to decision tree in Pydot

前端 未结 2 1862
礼貌的吻别
礼貌的吻别 2021-01-02 17:44

I have a dictionary object as such:

menu = {\'dinner\':{\'chicken\':\'good\',\'beef\':\'average\',\'vegetarian\':{\'tofu\':\'good\',\'salad\':{\'caeser\':\'b         


        
2条回答
  •  长发绾君心
    2021-01-02 18:44

    Using a recursive function

    You might want to consider using a recursive function (like the visit in my code below, so that you are able to process a general nested dictionary. In this function, you want to pass a parent parameter to keep track of who is your incoming node. Also note you use isinstance to check if the dictionary value of a key is a dictionary of its own, in that case you need to call your visit recursively.

    import pydot
    
    menu = {'dinner':
                {'chicken':'good',
                 'beef':'average',
                 'vegetarian':{
                       'tofu':'good',
                       'salad':{
                                'caeser':'bad',
                                'italian':'average'}
                       },
                 'pork':'bad'}
            }
    
    def draw(parent_name, child_name):
        edge = pydot.Edge(parent_name, child_name)
        graph.add_edge(edge)
    
    def visit(node, parent=None):
        for k,v in node.iteritems():
            if isinstance(v, dict):
                # We start with the root node whose parent is None
                # we don't want to graph the None node
                if parent:
                    draw(parent, k)
                visit(v, k)
            else:
                draw(parent, k)
                # drawing the label using a distinct name
                draw(k, k+'_'+v)
    
    graph = pydot.Dot(graph_type='graph')
    visit(menu)
    graph.write_png('example1_graph.png')
    

    Resulting tree structure

    enter image description here

提交回复
热议问题