8

In a multigraph each call to *add_edge(a,b,weight=1)* will add a new edge between nodes a and b. When building the graph, is it possible to modify this weight when a and b are found again. Right now I make a check to find whether (a, b) or (b, a) are connected, then have to delete the edge, and add a new one. It seems to me that I should simply be able to update the weight.

Note: I do need multigraphs because I use different types of edges between nodes (differentiated using key)

Vladtn
  • 2,506
  • 3
  • 27
  • 23

1 Answers1

14

The Multigraph.add_edge documentation indicates that you should use the key argument to uniquely identify edges in a multigraph. Here's an example:

>>> import networkx as nx
>>> G = nx.MultiGraph()
>>> G.add_edge(1, 2, key='xyz', weight=2)
>>> G.add_edge(1, 2, key='abc', weight=1)
>>> G.edges(data=True)
[(1, 2, {'weight': 2}), (1, 2, {'weight': 1})]

Now, to update the edge keyed by xyz, just pass that parameter in again:

>>> G.add_edge(1, 2, key='xyz', weight=7)
>>> G.edges(data=True)
[(1, 2, {'weight': 7}), (1, 2, {'weight': 1})]

To read the previous value, you can use get_edge_data like this:

>>> G.get_edge_data(1, 2, key='xyz')
{'weight': 7}
jterrace
  • 64,866
  • 22
  • 157
  • 202
  • Thanks! how do I retrieve the edges that correspond to the key? to know the previous value of _weight_ for example. Do I have to loop through all the edges to check the key first? – Vladtn Feb 27 '12 at 18:06
  • 2
    excuse me, but are there any ways to draw multigraph? I tried it do so: http://paste.org.ru/?o2jv6a But only one connection between two nodes is drawn – Tebe Oct 11 '12 at 06:10
  • You should ask that as a question. Off topic for this comment thread – jterrace Oct 11 '12 at 18:38
  • @E6aTb_E6aTb , jterrace is right, but in any case see [this answer](http://stackoverflow.com/a/17823100/1959808) and also [this answer](http://stackoverflow.com/a/15069150/1959808). – 0 _ Dec 27 '14 at 12:20