Dictionary object to decision tree in Pydot

独自空忆成欢 提交于 2019-11-30 15:18:24

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

Your question isn't entirely clear to me, but the way of accessing a dictionary key's value in Python is simply:

dictionary[key]

That will return to you that key's value. If that key is not in the dictionary, it will return a KeyError, so if you are working with dictionaries and you're not sure if the key you're requesting will be in the dictionary, you have two options.

If-statement (preferred):

if key in dictionary:
    return dictionary[key]

Try-catch:

try:
    return dictionary[key]
except KeyError:
    pass

If you don't know the keys in your dictionary and you need to get them, you can simply call dictionary.keys() and it will return a list of all of the keys in the dictionary.

Getting a the value of a dictionary key will return an object that could even be another object. Thus, to find out the value of "tofu", for example, we'd do the following:

menu['dinner']['vegetarian']['tofu']
# returns value 'good'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!