Reputation: 41
I'm using a dictionary to represent a graph in my Python program. I'm using the keys of the dictionary to represent 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?
Upvotes: 1
Views: 3516
Reputation: 11258
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]])
Upvotes: 1
Reputation: 7530
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]])
Upvotes: 5