Reputation: 19805
I have a dictionary which has the follower-followee information. For example:
a --> b,c,d
b --> c,d
c --> d
Here it means, a follows b,c,d. b follows c,d. c follows d. I have the following corresponding dictionary:
{'a': ['b', 'c', 'd'], 'b': ['c', 'd'], 'c': ['d']}
I want to create a directed graph out of this dictionary in igraph
.
What I am currently doing is:
import igraph
d = {'a': ['b', 'c', 'd'], 'b': ['c', 'd'], 'c': ['d']}
edges = []
vertices_set = set()
for key in d:
vertices_set.add( key )
for item in d[key]:
edges.append( (key, item) )
vertices_set.add( item )
# vertices_set: set(['a', 'c', 'b', 'd'])
# edges: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('c', 'd'), ('b', 'c'), ('b', 'd')]
g = igraph.Graph( directed=True )
g.add_vertices( len(vertices_set) )
g.vs['name'] = list(vertices_set)
g.add_edges( edges )
print(len(g.vs))
print(len(g.es))
And this code works as expected. However, it is rather ugly (and most likely slower than it should be) as you can see.
I feel like, there should a faster and/or more pythonic way of doing this. Any comments?
Upvotes: 1
Views: 686
Reputation: 48051
You can make use of the Graph.TupleList
function:
>>> from igraph import Graph
>>> d = {'a': ['b', 'c', 'd'], 'b': ['c', 'd'], 'c': ['d']}
>>> g = Graph.TupleList([(k, v) for k, vs in d.iteritems() for v in vs])
>>> print g
IGRAPH UN-- 4 6 --
+ attr: name (v)
+ edges (vertex names):
a -- b, c, d b -- a, c, d c -- a, b, d d -- a, b, c
Upvotes: 3