我有一个带有networkx
边缘的元组列表,这些元素保证是树状的:
[('king', 'governor'),
('governor', 'editor'),
('king', 'state'),
('state', 'collapse'),
('collapse', 'coverage'),
('collapse', 'author'),
('collapse', 'opening'),
('state', 'head'),
('state', 'lord')]
这些按深度优先搜索顺序进行排序,但如果这样可以更容易地按广度优先顺序进行排序。
我正在寻找一种将这个边缘列表转换为JSON对象的方法。上一个例子将成为:
{'king': [{'governor': [{'editor': []}]},
{'state': [{'collapse': [{'coverage': []},
{'author': []},
{'opening': []}]},
{'head': []},
{'lord': []}]
}]
}
叶子节点是否应该像示例输出中那样表示为dict,或者只是表示为字符串,取决于您。如果使用networkx.DiGraph
比使用边缘列表更容易地执行此操作,那么这也可以正常工作。
感谢任何帮助。
答案 0 :(得分:1)
import json
data = [('king', 'governor'),
('governor', 'editor'),
('king', 'state'),
('state', 'collapse'),
('collapse', 'coverage'),
('collapse', 'author'),
('collapse', 'opening'),
('state', 'head'),
('state', 'lord')];
root = data[0][0]
node2chilren = {root: []}
for parent, child in data:
childnode = {child: []}
children = node2chilren[parent]
children.append(childnode)
node2chilren[child] = childnode[child]
jsonstr = json.dumps({root: node2chilren[root]}, indent=4)
print jsonstr
输出
{
"king": [
{
"governor": [
{
"editor": []
}
]
},
{
"state": [
{
"collapse": [
{
"coverage": []
},
{
"author": []
},
{
"opening": []
}
]
},
{
"head": []
},
{
"lord": []
}
]
}
]
}