Как преобразовать словарь в объекты класса attr-child? - PullRequest
0 голосов
/ 15 мая 2018

У меня есть dict, который имеет древовидную структуру.Я хочу, чтобы это было преобразовано в отношения атрибут-потомок, определенные моим конструктором.

Так выглядит мой класс -

class DecisionNode:

# A DecisionNode contains an attribute and a dictionary of children. 
# The attribute is either the attribute being split on, or the predicted label if the node has no children.
def __init__(self, attribute):
    self.attribute = attribute
    self.children = {}

Мой код можно найти здесь - https://raw.githubusercontent.com/karthikkolathumani/Machine-Learning-Models/master/id3.py

Это фиктивный метод, который имитирует то, что мне действительно нужно сделать с моим объектом словаря -

def funTree():
    myLeftTree = DecisionNode('humidity')
    myLeftTree.children['normal'] = DecisionNode('no')
    myLeftTree.children['high'] = DecisionNode('yes')
    myTree = DecisionNode('wind')
    myTree.children['weak'] = myLeftTree
    myTree.children['strong'] = DecisionNode('no')
    return myTree

Пример вывода выглядит примерно так (пример) -

 wind = weak
     humidity = normal:  no
     humidity = high:  yes
 wind = strong:  no

Пример объекта Dict -

{'outlook': {'sunny': {'temperature': {'hot': 'no', 'mild': {'humidity': {'high': 'no', 'normal': 'yes'}}, 'cool': 'yes'}}, 'overcast': 'yes', 'rainy': {'temperature': {'mild': {'humidity': {'high': {'wind': {'weak': 'yes', 'strong': 'no'}}, 'normal': 'yes'}}, 'cool': {'humidity': {'normal': {'wind': {'weak': 'yes', 'strong': 'no'}}}}}}}}

Мой текущий результат выглядит так, где я использую selfattr

outlook =
        sunny =
                temperature =
                        hot = no
                        mild =
                                humidity =
                                        high = no
                                        normal = yes
                        cool = yes
        overcast = yes
        rainy =
                temperature =
                        mild =
                                humidity =
                                        high =
                                                wind =
                                                        weak = yes
                                                        strong = no
                                        normal = yes
                        cool =
                                humidity =
                                        normal =
                                                wind =
                                                        weak = yes
                                                        strong = no
...