Create Nodes From Keys And Edges From The Values From A Dictionary Networkx
I'm stuck trying to solve a problem that I encounter. As mentioned in this post the nx.Graph() function can take a dictionary as an initialising argument. Which works fine, but I h
Solution 1:
It appears that what you want is a Multigraph, given that you want to have nodes with multiple edges. In that case, and following the logic you've described, you want to check for all pair of nodes (keys
), which values are shared among them, and use these as edges connecting those nodes. For that we could find the length 2
combinations of all keys, and find the set.intersection
of their values to set the paths:
from itertools import combinations
graph = {'A': ['a','b','c'], 'B':['a','b','c']}
G = nx.MultiGraph()
for nodes incombinations(graph.keys(), r=2):
common_edges = set(graph[nodes[0]]) & set(graph[nodes[1]])
for edge in common_edges:
G.add_edge(*nodes, value=edge)
If you wanted to visualise the graph, you could use Graphviz
which does display parallel edges. You could write the graph to dot
format and save it as a png
with:
nx_pydot.write_dot(G, 'multig.dot')
!dot -T png multig.dot > multig.png
Post a Comment for "Create Nodes From Keys And Edges From The Values From A Dictionary Networkx"