将字典显示为树?

时间:2016-09-23 02:27:51

标签: python dictionary

我有一本字典,我希望以特定的格式显示它。

这是我的字典:

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

我想将其显示为:

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

我对字典和Python很新,我不知道如何显示它们。

2 个答案:

答案 0 :(得分:3)

如果没有递归,这将非常接近,尽管它可能很脆弱

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)

输出:

    (.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
 | |
 |

您可以使用.replace()来调用它以使其恰到好处。

答案 1 :(得分:3)

这将输出您想要的内容。

# If you are not using Python 3
from __future__ import print_function

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

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def go(dic, last_key, current_level):
    for key, value in dic.items():
        if is_number(key):
            for i in range(current_level - 1):
                print("| ", end="")

            print(last_key, "= ", end="")
            print(key, ": ", end="")
        else:
            if current_level > 0:
                print("")

            current_level = current_level + 1

        if isinstance(value, dict):
            go(value, key, current_level)
        else:
            print(value)

go(tree, None, 0)

输出:

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