从字典 Networkx 中的键和边创建节点 [英] Create nodes from keys and edges from the values from a dictionary Networkx

查看:52
本文介绍了从字典 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 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.

解决方案

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

这篇关于从字典 Networkx 中的键和边创建节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆