使用 networkx 绘制字典字典

plot a dictionary of dictionary using networkx

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

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'}}

       }}

我想绘制网络并查看连接到的每个节点 我使用了 networkx 中的 from_dict_of_dicts 方法并且它有效但它没有显示最终的 dict 例如aaa201,aaa101 但只显示这两个值的键

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

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

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()

输出: