字典对象到决策树在Pydot中 [英] Dictionary object to decision tree in Pydot

查看:72
本文介绍了字典对象到决策树在Pydot中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字典对象:

I have a dictionary object as such:

menu = {'dinner':{'chicken':'good','beef':'average','vegetarian':{'tofu':'good','salad':{'caeser':'bad','italian':'average'}},'pork':'bad'}}

我正在尝试使用pydot和'menu'数据创建图形(决策树)

I'm trying to create a graph (decision tree) using pydot with the 'menu' data this.

晚餐"将是顶部节点,其值(鸡肉,牛肉等)位于其下方.参考该链接,graph函数采用两个参数:源和节点.

'Dinner' would be the top node and its values (chicken, beef, etc.) are below it. Referring to the link, the graph function takes two parameters; a source and a node.

类似于:

除了国王"将是晚餐",主"将是鸡肉",牛肉"等.

Except 'king' would be 'dinner' and 'lord' would be 'chicken', 'beef', etc.

我的问题是:如何访问值中的键?为了从这些数据创建树,我觉得我需要创建一个循环,以检查特定键是否存在值并对其进行绘制.我不确定如何为任何字典对象调用值(如果它不一定称为晚餐"或具有尽可能多的元素.).

My question is: How do I access a key in a value? To create a tree from this data I feel like I need to create a loop which checks if there is a value for a specific key and plots it. I'm not sure how to call values for any dictionary object (if it's not necessarily called 'dinner' or have as many elements.).

关于如何绘制图形的任何建议?

Any suggestions on how to graph it?

推荐答案

使用递归函数

您可能要考虑使用递归函数(例如下面的代码中的visit,以便能够处理常规的嵌套字典.在此函数中,您希望传递parent参数来跟踪谁是您的传入节点.还请注意,您使用isinstance检查密钥的字典值是否是其自己的字典,在这种情况下,您需要递归调用visit

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')

生成的树结构

这篇关于字典对象到决策树在Pydot中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆