[英]Create jstree hierarchy from parent child pair from table
I have a parent child pair from table, example: 我有一个父母对表,例如:
links=(("Tom","Dick"),
("Dick","Harry"),
("Tom","Larry"),
("Bob","Leroy"),
("Bob","Earl"),
("Earl","Joy"),
("Joy","Joy child"),
("Joy","Joy child2"),
("Joy child2", "Maria"))
and I am trying to create jstree from this pairs. 我正在尝试从这对创建jstree。 I went through various links but cant get this tuple to work.
我通过各种链接,但无法使该元组正常工作。 Can anyone please provide a recursive function in python which takes the tuple as mentioned above or any combination of parent-child-grand-child pairs as input and creates a hierarchy by creating a json similar to this format
任何人都可以在python中提供一个递归函数,该函数采用上述元组或父子孙子对的任意组合作为输入,并通过创建类似于此格式的json创建层次结构
{
"name": "Tom",
"children": [
{
"name": "Dick"
}
]
}
Thank you in Advance:) I really appreciate your help! 在此先感谢您:)非常感谢您的帮助!
import json
links = (("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Tom","Hurbert"),("Tom","Neil"),("Bob","Leroy"),("Bob","Earl"),("Tom","Reginald"))
name_to_node = {}
root = {'name': 'Root', 'children': []}
for parent, child in links:
parent_node = name_to_node.get(parent)
if not parent_node:
name_to_node[parent] = parent_node = {'name': parent}
root['children'].append(parent_node)
name_to_node[child] = child_node = {'name': child}
parent_node.setdefault('children', []).append(child_node)
print json.dumps(root, indent=4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.