使用networkx绘制字典的字典

2024-09-27 22:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这本词典,里面有两本词典

tdict={'a1':{
    'aa1':{'aaa101':{'information'},'aaa201':{'information'}},
    'aa2':{'cca101':{'information'},'aca201':{'information'}},
    'ab1':{'aasdfaa101':{'information'},'aadaa201':{'information'}}
}
       ,'a2':{
           'ab1':{'aasdfaa101':{'information'},'aadaa201':{'information'}},
           'ab2':{'zz101':{'information'},'azz201':{'information'}},
           'ac2':{'aaa101':{'information'},'aaa201':{'information'}}
       }
       ,'a3':{
           'ac1':{'aaa101':{'information'},'aaa201':{'information'}},
           'ac2':{'aaa101':{'information'},'aaa201':{'information'}}

       }}

我想绘制网络图并查看连接到的每个节点,我使用了来自networkxfrom_dict_of_dicts方法,它可以工作,但它不显示最终的dict,例如aaa201,aaa101,而只显示这两个值的键

enter image description here

如何将节点aaa201,zz101包含在同一个绘图中


Tags: 节点informationa1dicttdictaa2aa1本词典
1条回答
网友
1楼 · 发布于 2024-09-27 22:20:37

可以使用递归遍历字典,并使用节点和相应边填充图形:

import networkx as nx
import matplotlib.pyplot as plt
tdict = {'a1': {'aa1': {'aaa101': {'information'}, 'aaa201': {'information'}}, 'aa2': {'cca101': {'information'}, 'aca201': {'information'}}, 'ab1': {'aasdfaa101': {'information'}, 'aadaa201': {'information'}}}, 'a2': {'ab1': {'aasdfaa101': {'information'}, 'aadaa201': {'information'}}, 'ab2': {'zz101': {'information'}, 'azz201': {'information'}}, 'ac2': {'aaa101': {'information'}, 'aaa201': {'information'}}}, 'a3': {'ac1': {'aaa101': {'information'}, 'aaa201': {'information'}}, 'ac2': {'aaa101': {'information'}, 'aaa201': {'information'}}}}
G = nx.Graph()
def create_graph(d, g, p = None):
   for a, b in d.items():
      g.add_node(a)
      if p is not None:
         g.add_edge(p, a)
      if not isinstance(b, set):
         create_graph(b, g, a)

create_graph(tdict, G)
nx.draw(G, with_labels = True)
plt.show()

输出:

enter image description here

相关问题 更多 >

    热门问题