Search code examples
graphadditionnetworkxgraph-theoryedge-list

How can I add a second new edge between two nodes update the old one


What I have: a multigraph H in networkX. Two nodes '0' and '1'. An existing edge e1=(0,1).

What I want: add a second new edge e2 between nodes 0 and 1.

PROBLEM: When I add the new edge e2 between 0 and 1, e1 is updated whit the new value (attributes) of e2, and e2 is not added. There is always a single edge between 0 and 1

My example code:

H=nx.MultiGraph()
H=nx.read_gml('my_graph.gml')

If I print all the edges of H I correctly have this:

for i in H.edges(data=True):
    print i
    >>>>>(0, 1, {})   #this is ok 

Now I add a new edge to e2=(0,1) using the key attribute:

H.add_edge(0,1,key=1,value='blue')

But if i print all the edges of H:

for i in H.edges(data=True):
    print i
    >>>>>(0, 1, {'key': 1, 'value': 'blue'})  #this is error e1 was updated instead add of e2

As you can see, the second edge has update the first one, but e2 was added with a specified key, different form e1 (default is 0).

How can I avoid this problem?? I Want this result after adding edge e2:

for i in H.edges(data=True):
    print i
    >>>>>(0: 0, 1, {}, 1: 0,1,{'value': 'blue'} )  #this is correct 

Solution

  • You don't have a multigraph so you are replacing edges instead of adding new ones. Use

    H=nx.MultiGraph(nx.read_gml('my_graph.gml'))