'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. The same is the case for node2 it links with node 2_1,node2_2, and node2_3 along with their respective weights. Is there any generalized way to generate a directed graph from the input dictionary using NetworkKx or through any other way in Python?
Solution 1:[1]
IIUC, you can use 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:
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

