简体   繁体   English

从嵌套字典生成 Python 中的网络图

[英]Generate Network Graph in Python from nested dictionary

I have an input dictionary like:我有一个输入字典,如:

d={'node1':{'node1_1':1.2,'node1_2':1.3,'node1_3':1.2},'node2': 
           {'node2_1':1.3,'node2_2':1.3,'node2_3':1.4}}

In the output, node1 has a relationship with node1_1 with a weight of 1.2, node1_2 with a weight of 1.3, and node 1-3 with a weight of 1.2. output中,node1与权重为1.2的node1_1、权重为1.3的node1_2、权重为1.2的节点1-3有关系。 The same is the case for node2 it links with node 2_1,node2_2, and node2_3 along with their respective weights. node2 的情况也是如此,它与节点 2_1、node2_2 和 node2_3 以及它们各自的权重相关联。 Is there any generalized way to generate a directed graph from the input dictionary using NetworkKx or through any other way in Python?是否有任何通用方法可以使用 NetworkKx 或通过 Python 中的任何其他方式从输入字典生成有向图?

IIUC, you can use nx.from_dict_of_lists : IIUC,你可以使用nx.from_dict_of_lists

d={'node1':{'node1_1':1.2,'node1_2':1.3,'node1_3':1.2},
   'node2':{'node2_1':1.3,'node2_2':1.3,'node2_3':1.4}}

import networkx as nx
G = nx.from_dict_of_lists(d, create_using=nx.DiGraph)

To have the weights, use nx.from_dict_of_dicts :要获得权重,请使用nx.from_dict_of_dicts

d2 = {k:{k2: {'weight': v2} for k2,v2 in v.items()} for k,v in d.items()}
G = nx.from_dict_of_dicts(d2, create_using=nx.DiGraph)

output: output:

nextworkx 图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM