将嵌套字典转换为可图形化的格式

时间:2018-07-26 20:19:02

标签: json python-3.x dictionary

所以我正在尝试转换一个嵌套字典,如:

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"}]
       }
    ]
}

我需要这个,因为我正在尝试使用以下图形绘制模板对其进行可视化:Collapsible Tree

我在创建能够进行这种转换的递归方法时遇到了麻烦。

最好在python3中使用。到目前为止,我有:

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

但是它是错误的。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

我们将有一个函数以根(假设它只有一个条目)并返回一个字典,以及一个帮助函数,该函数返回字典列表。

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"
        }
      ]
    }
  ]
}