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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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:
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
