Rohith Reddy Rohith Reddy - 2 months ago 8
Python Question

Display a dictionary as a tree?

This is my dictionary:

tree = {'wesley': {'0': {'romulan': {'0': {'poetry': {'0': {'honor': {'0': '0',
'1': '1'}},
'1': {'honor': {'0': '1',
'1': '0'}}}},
'1': '0'}},
'1': {'romulan': {'0': '1', '1': '0'}}}}


I want it to display as:

wesley = 1 :
| romulan = 1 : 0
| romulan = 0 : 1
wesley = 0 :
| romulan = 1 : 0
| romulan = 0 :
| | poetry = 1 :
| | | honor = 1 : 0
| | | honor = 0 : 1
| | poetry = 0:
| | | honor = 1 : 1
| | | honor = 0 : 0


I am very new to dictionaries and python and have no knowledge of how to display them.

Answer

This will get it pretty close without recursion, though it's potentially brittle

import json

tree = {'wesley': {'1': {'romulan': {'1': '0', '0': '1'}}, '0':    {'romulan': {'1': '0', '0': {'poetry': {'1': {'honor': {'1': '0', '0': '1'}}, '0': {'honor': {'1': '1', '0': '0'}}}}}}}}


tree_str = json.dumps(tree, indent=4)
tree_str = tree_str.replace("\n    ", "\n")
tree_str = tree_str.replace('"', "")
tree_str = tree_str.replace(',', "")
tree_str = tree_str.replace("{", "")
tree_str = tree_str.replace("}", "")
tree_str = tree_str.replace("    ", " | ")
tree_str = tree_str.replace("  ", " ")

print(tree_str)

Output:

    (.venv35) ➜  stackoverflow python weird_formated_print.py

wesley:
 | 0:
 | | romulan:
 | | | 0:
 | | | | poetry:
 | | | | | 0:
 | | | | | | honor:
 | | | | | | | 0: 0
 | | | | | | | 1: 1
 | | | | | |
 | | | | |
 | | | | | 1:
 | | | | | | honor:
 | | | | | | | 0: 1
 | | | | | | | 1: 0
 | | | | | |
 | | | | |
 | | | |
 | | |
 | | | 1: 0
 | |
 |
 | 1:
 | | romulan:
 | | | 0: 1
 | | | 1: 0
 | |
 |

You could play around with the .replace() calls to get it just right.