python - Recursive seek throught python dictionary to create Graphviz
问题描述
I've got dictionary with such body:
[
{
"children": [
{
"children": [
{
"children": [
{
"label": "Something20",
"id": 11
},
{
"label": "Something19",
"id": 12
}
],
"label": "Something18",
"id": 5
},
{
"children": [
{
"label": "Something15",
"id": 13
}
],
"label": "Something14",
"id": 6
}
],
"label": "Something2",
"id": 2
},
{
"children": [
{
"children": [
{
"label": "Something10",
"id": 14
}
],
"label": "Something9",
"id": 7
},
{
"label": "Something8",
"id": 8
}
],
"label": "Somethin7",
"id": 3
},
{
"children": [
{
"label": "Something5",
"id": 9
},
{
"label": "Something4",
"id": 10
}
],
"label": "Something2",
"id": 4
}
],
"label": "Something1",
"id": 1
}
]
How can I recursively seek through this dict to generate Graphviz data like this:
Something1->Something2
Something1->Something7
So e.g. list called edges = []
and append to it some data as touples (only labels):
[("Something1", "Something2"), ("Something1", "Something7")]
After data is generated I can then simply generate object in Graphviz (Generate PNG Image) representing tree structure of provided dictionary.
解决方案
如果您想递归地执行此操作,您可以有一个函数,该函数从节点生成一条边,并将其传递给它的每个子节点,并为每个子节点调用自身。然后您需要做的就是为根列表中的每个节点调用它(并且您需要在列表中收集所有生成的边)。这可以按如下方式实现(root
保存您的数据):
def get_edges(node):
if "children" not in node: # ensure the node has children
return []
label = node["label"]
children = node["children"]
result = [(label, c["label"]) for c in children] # create the edges
for c in children:
result.extend(get_edges(c)) # travers the tree recursively and collect all edges
return result
edges = sum(map(get_edges, root), []) # create and combine all the edge lists
使用您提供的数据运行此代码会产生以下结果:
[('Something1', 'Something2'), ('Something1', 'Somethin7'),
('Something1', 'Something2'), ('Something2', 'Something18'),
('Something2', 'Something14'), ('Something18', 'Something20'),
('Something18', 'Something19'), ('Something14', 'Something15'),
('Somethin7', 'Something9'), ('Somethin7', 'Something8'),
('Something9', 'Something10'), ('Something2', 'Something5'),
('Something2', 'Something4')]
推荐阅读
- docker - 如何使用 Keycloak jboss/keycloak:15.0.2 docker 镜像?
- javascript - 如何修复 Uncaught (in promise) DOMException: The user aborted a request SoundCloud widget Api
- r - 卡住使用 mirt 包中的 multipleGroup 和 DIF 函数
- python - 使用 PolynomialFeatures 类的 get_feature_names() 方法确定您计算了哪些系数
- mongoose - 为什么模式方法不能是 ES6 箭头函数
- javascript - 如何获得满足条件的两个对象键的总和
- python - 在 Python 中保存和重新分配全局变量 dict
- javascript - 如何在 Mongoose 中优化以下查询?
- python - 正则表达式用于使用 OPTIONAL SEPARATOR (char) 拆分字符串
- java - java:重定位错误:jdk180_301/jre/lib/amd64/libnio.so:符号 initInetAddressIDs,版本 SUNWprivate_1.1 未在文件 libnet.so 中定义