Create nodes from keys and edges from the values from a dictionary Networkx

守給你的承諾、 提交于 2020-06-28 03:59:08

问题


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 had something different in mind.

My dictionary looks as follows (contents simplified):

graph = {'A': ['a','b','c'], 'B':['a','b','c']}

This creates the following: plot

As can be seen for 'B', 'A', 'a', 'b' and 'c' nodes have been created. What I am looking for is a way to initialise the keys in my dictionary as nodes and the values as edges. This would result in a network of two nodes with three edges as both 'A' and 'B' contain 'a', 'b' and 'c'.

Maybe the solution is quite simple but after staring myself blind at the documentation I hope someone here has the answer, all help is welcome.


回答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 in combinations(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



来源:https://stackoverflow.com/questions/61388452/create-nodes-from-keys-and-edges-from-the-values-from-a-dictionary-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!