Json 将嵌套字典转换为可绘图格式
因此,我尝试转换嵌套字典,如:Json 将嵌套字典转换为可绘图格式,json,python-3.x,dictionary,Json,Python 3.x,Dictionary,因此,我尝试转换嵌套字典,如: A = { "root": { "child1": { "child11":"hmm", "child12":"not_hmm" }, "child2":"hello" } } 为此: { "name":"root", "children": [ {"name":"child1", "childr
A = {
"root":
{
"child1":
{
"child11":"hmm",
"child12":"not_hmm"
},
"child2":"hello"
}
}
为此:
{
"name":"root",
"children": [
{"name":"child1",
"children" :
[{"name":"child11",
"children":[{"name":"hmm"}]}
{"name":"child12",
"children":[{"name":"not_hmm"}]}
]
},
{"name":"child2",
"children":[{"name":"hello"}]
}
]
}
我需要这个,因为我正试图用这个图形绘制模板将其可视化:
我在创建能够进行这种转换的递归方法时遇到了一些问题
最好是在蟒蛇3。到目前为止,我已经:
def visit(node, parent=None):
B = {}
for k,v in node.items():
B["name"]=k
B["children"] = []
if isinstance(v,dict):
print("Key value pair is",k,v)
B["children"].append(visit(v,k))
new_dict = {}
new_dict["name"]=v
return [new_dict]
C = visit(A) # This should have the final result
但这是错误的。非常感谢您的帮助。我们将有一个以根为根(假设只有一个条目)并返回dict的函数,以及一个返回dict列表的帮助函数
def convert(d):
for k, v in d.items():
return {"name": k, "children": convert_helper(v)}
def convert_helper(d):
if isinstance(d, dict):
return [{"name": k, "children": convert_helper(v)} for k, v in d.items()]
else:
return [{"name": d}]
这给了我们
json.dumps(convert(A), indent=2)
{
"name": "root",
"children": [
{
"name": "child1",
"children": [
{
"name": "child11",
"children": [
{
"name": "hmm"
}
]
},
{
"name": "child12",
"children": [
{
"name": "not_hmm"
}
]
}
]
},
{
"name": "child2",
"children": [
{
"name": "hello"
}
]
}
]
}