Alan Valejo
Alan Valejo

Reputation: 1315

How to add edges in an igraph object from a dictionary

I'm using a dictionary to represent a set of edges. I'm using the keys of the dictionary to represent edges and the values to represent the weights. The dictionary currently looks like this:

{(0, 1): 2, (1, 2): 6, (0, 2): 3}

I try this:

edges, weights = [], []
for edge, weight in dict_edges.items():
    edges += [edge]
    weights.append(weight)

g.add_edges(edges)
g.es["weight"] = weights

But, I don't if there is a faster way or more cleaner to do this.

Anyone have any suggestions how to improve my new?

Upvotes: 1

Views: 859

Answers (1)

Tamás
Tamás

Reputation: 48101

What you do is perfectly fine; maybe the for loop could be replaced with a zip call. If you are using Python 2.x::

from itertools import izip
edges, weights = izip(*dict_edges.iteritems())
g = Graph(edges, edge_attrs={"weight": weights})

If you are using Python 3.x::

edges, weights = zip(*dict_edges.items())
g = Graph(edges, edge_attrs={"weight": weights})

Upvotes: 3

Related Questions