【问题标题】:Convert Nested Dictionary to a graphable format将嵌套字典转换为图形格式
【发布时间】:2018-07-26 20:19:02
【问题描述】:

所以我正在尝试将嵌套字典转换为:

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

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

【问题讨论】:

    标签: json python-3.x dictionary


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2020-09-03
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多