Issue
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
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:
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.