2

I have a dict of dicts that have links from one nested dict to another. It represents a decision tree. The goal is to visualize it. This code is a simplified version of what I have:

decision_tree_1 = {
0:{'Q':'Do you like fruit or vegetables?', 'A':{'Fruit': 1, 'Vegetables': 2}},
1:{'Q':'Apples or oranges?', 'A':{'Apples': 11, 'Oranges': 12}},
11:{'Q':'Have an apple', 'A':{}},
12:{'Q':'Have an orange', 'A':{}},
2:{'Q':'Have a salad', 'A':{}}
}

I think the best way to visualize it is to transform the code into JSON like code. So I mannualy rewrote it to this:

decision_tree_2 = {
 "A": "",
 "Q": "Do you like fruit or vegetables?",
 "children": [
  {
   "A": "Fruit",
   "Q": "Apples or oranges?",
   "children": [
      {
       "A": "Apples",
       "Q": "Have an apple",
       "children": ""
      },
      {
       "A": "Oranges",
       "Q": "Have an orange",
       "children": ""
      }
    ]
  },
  {
   "A": "Vegetables",
   "Q": "Have a salad",
    "children": ""
  }
 ]
}

This second structure is then easy to visualize. So is it possible to automatically trasform code from decision_tree_1 into code from decision_tree_2?

J.K.
  • 555
  • 4
  • 8

1 Answers1

1

You can use recursion:

decision_tree_1 = {0: {'Q': 'Do you like fruit or vegetables?', 'A': {'Fruit': 1, 'Vegetables': 2}}, 1: {'Q': 'Apples or oranges?', 'A': {'Apples': 11, 'Oranges': 12}}, 11: {'Q': 'Have an apple', 'A': {}}, 12: {'Q': 'Have an orange', 'A': {}}, 2: {'Q': 'Have a salad', 'A': {}}}
def restructure(nid, a = ""):
   return {'A':a, 
           'Q':decision_tree_1[nid]['Q'], 
           'children':'' if not (c:=decision_tree_1[nid]['A']) else 
               [restructure(b, a) for a, b in c.items()]}

import json
print(json.dumps(restructure(0), indent=4))

Output:

{
    "A": "",
    "Q": "Do you like fruit or vegetables?",
    "children": [
        {
            "A": "Fruit",
            "Q": "Apples or oranges?",
            "children": [
                {
                    "A": "Apples",
                    "Q": "Have an apple",
                    "children": ""
                },
                {
                    "A": "Oranges",
                    "Q": "Have an orange",
                    "children": ""
                }
            ]
        },
        {
            "A": "Vegetables",
            "Q": "Have a salad",
            "children": ""
        }
    ]
}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102