如何使用 Python 以更易读的树格式打印下面的字典数据,如下所示。这是我第一次来这里,请原谅我的无知。
TempDict =
{'outlook': {'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}, 'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}}, 'overcast': 'yes'}}
Run Code Online (Sandbox Code Playgroud)
所需的输出格式 -
outlook=sunny
humidity=high:no
humidity=normal:yes
outlook=rainy
wind=strong:no
wind=weak:yes
Run Code Online (Sandbox Code Playgroud)
像这样打印的类:
class DecisionNode:
def __init__(self, attribute):
self.attribute = attribute
self.children = {}
# Visualizes the tree
def display(self, level = 0):
if self.children == {}:
# reached leaf level
print(": ", self.attribute, end="")
else:
for value in self.children.keys():
prefix = "\n" + " " * level * 4
print(prefix, self.attribute, "=", value, end="")
self.children[value].display(level + 1)
Run Code Online (Sandbox Code Playgroud)
您需要递归地运行您的数据!
temp = {'outlook': {'sunny': {'humidity': {'high': [ 'no' ,1 ] , 'normal': 'yes'}}, 'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}}, 'overcast': 'yes'}}
def formatData(t,s):
if not isinstance(t,dict) and not isinstance(t,list):
print "\t"*s+str(t)
else:
for key in t:
print "\t"*s+str(key)
if not isinstance(t,list):
formatData(t[key],s+1)
formatData(temp,0)
Run Code Online (Sandbox Code Playgroud)
输出:
outlook
rainy
wind
strong
no
weak
yes
overcast
yes
sunny
humidity
high
no
1
normal
yes
Run Code Online (Sandbox Code Playgroud)
您还可以使用pprint
import pprint
pprint.pprint(myvar)
Run Code Online (Sandbox Code Playgroud)
示例输出:
{'outlook': {'overcast': 'yes',
'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}},
'sunny': {'humidity': {'high': ['no', 1], 'normal': 'yes'}}}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9108 次 |
| 最近记录: |