SoFunction
Updated on 2024-11-12

Example of a python dictionary generating a tree diagram

python dictionary to generate a tree diagram

from graphviz import Digraph

# Get the leaf node with the most children of all nodes
def getMaxLeafs(myTree):
    numLeaf = len(())
    for key, value in ():
        if isinstance(value, dict):
            sum_numLeaf = getMaxLeafs(value)
            if sum_numLeaf > numLeaf:
                numLeaf = sum_numLeaf
    return numLeaf

def plot_model(tree, name):
    g = Digraph("G", filename=name, format='png', strict=False)
    first_label = list(())[0]
    ("0", first_label)
    _sub_plot(g, tree, "0")
    leafs = str(getMaxLeafs(tree) // 10)
    (rankdir='LR', ranksep=leafs)
    ()

root = "0"


def _sub_plot(g, tree, inc):
    global root

    first_label = list(())[0]
    ts = tree[first_label]
    for i in ():
        if isinstance(tree[first_label][i], dict):
            root = str(int(root) + 1)
            (root, list(tree[first_label][i].keys())[0])
            (inc, root, str(i))
            _sub_plot(g, tree[first_label][i], root)
        else:
            root = str(int(root) + 1)
            (root, tree[first_label][i])
            (inc, root, str(i))

tree = {
        "tearRate": {
            "reduced": "no lenses",
            "normal": {
                "astigmatic": {
                    "yes": {
                        "prescript": {
                            "myope": "hard",
                            "hyper": {
                                "age": {
                                    "young": "hard",
                                    "presbyopic": "no lenses",
                                    "pre": "no lenses"
                                }
                            }
                        }
                    },
                    "no": {
                        "age": {
                            "young": "soft",
                            "presbyopic": {
                                "prescript": {
                                    "myope": "no lenses",
                                    "hyper": "soft"
                                }
                            },
                            "pre": "soft"
                        }
                    }
                }
            }
        }
    }
plot_model(tree, "")

The effect is as follows:

python spanning tree structure

# Generate a tree structure
def get_trees(data,
              key_column='elementId',
              parent_column='parentId',
              child_column='children'):
    """
    :param data: list of data
    :param key_column: primary key field, default id
    :param parent_column: parent id field name, default id of parent starts from 0
    :param child_column: child list dictionary name
    :return: tree structure
    """
    data_dic = {}
    for d in data:
        data_dic[(key_column)] = d  # Construct a new dictionary using your own privilege key as the key and the newly constructed dictionary as the value.
 
    data_tree_list = []  # The whole big list of data
    for d_id, d_dic in data_dic.items():
        pid = d_dic.get(parent_column)  # Take the parent id in each dictionary
        if not pid:  # parent id=0, just add it to the big list of data
            data_tree_list.append(d_dic)
        else:  # parent id>0 join the node list of the one corresponding to the parent id team.
            try:  # Determine if the exception represents a child node, add a list of child nodes = []
                data_dic[pid][child_column].append(d_dic)
            except KeyError:
                data_dic[pid][child_column] = []
                data_dic[pid][child_column].append(d_dic)
    return data_tree_list
 
def recursion(data, l=None):
    if l is None:
        l = []
    for i in data:
        if 'children' in i:
            children=('children')
            (i)
            recursion(children,l)
        else:
            (i)
    return l

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.