开发者

How to create an igraph object from a dictionary in Python

开发者 https://www.devze.com 2023-02-21 14:56 出处:网络
I\'m using a dictionary to represent a graph in my Python program. I\'m using the keys of the dictionary to repres开发者_如何学Cent vertices and the values to represent the adjacent nodes of each vert

I'm using a dictionary to represent a graph in my Python program. I'm using the keys of the dictionary to repres开发者_如何学Cent vertices and the values to represent the adjacent nodes of each vertex. The dictionary currently looks like this:

{  
   'v1' : ['v2','v3'],
   'v2' : ['v1'],
   'v3' : ['v1','v4'],
   'v4' : ['v3']
    // And so on. 
}

Is there a straightforward way to create a new igraph object from this dictionary? If there's no easy way, what's the next-best option?


Well, according to the docs, it seems that igraph expects vertices encoded as integers. So you need to specify a mapping from your vertices to integers and then you could actually proceed for example like this:

G= {'v1': ['v2', 'v3'], 'v2': ['v1'], 'v3': ['v1', 'v4'], 'v4': ['v3']}
mvi= {'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}
graph= igraph.Graph(edges= [(mvi[v], mvi[a]) for v in G.keys() for a in G[v]])


I did something like this which imports names of vertices to the graph also:

relations = {'v1': ['v2','v3'], 'v2': ['v1'], 'v3': ['v1','v4']}
g = igraph.Graph()
g.add_vertices(list(set(list(relations.keys()) + list([a for v in relations.values() for a in v]))))
g.add_edges([(v, a) for v in relations.keys() for a in relations[v]])
0

精彩评论

暂无评论...
验证码 换一张
取 消