user32882
user32882

Reputation: 5877

Networkx: get_edge_data returning unexpected result when ca;lled on MultiDiGraph

I am using Python's popular network library networkx. From the following code I expect the printed statements to be equivalent.

import networkx as nx

graph = nx.Graph()
mgraph =  nx.MultiDiGraph()

for G in [graph, mgraph]:
    G.add_edge(1, 2, weight=4.7)

print(graph.get_edge_data(1, 2))
print(mgraph.get_edge_data(1,2))

However I obtain the following:

{'weight': 4.7}
{0: {'weight': 4.7}}

Why is that extra 0 key added in the case of the multidirectional graph? What does it correspond to?

Upvotes: 1

Views: 279

Answers (1)

Joel
Joel

Reputation: 23827

A MultiDiGraph allows multiple edges. Each edge may have its own attributes. In your example what it is telling you is that in the Graph case, the edge (of which there can be only one) has weight 4.7. But in the MultiDiGraph case it is telling you that the edge which is indexed by 0 (and there happens to be only this single edge) has weight 4.7.

Try this to get a bit more clarity where we add the edge again, but with a different weight:

import networkx as nx

graph = nx.Graph()
mgraph =  nx.MultiDiGraph()

for G in [graph, mgraph]:
    G.add_edge(1, 2, weight=4.7)
    G.add_edge(1, 2, weight = 5)  #are we overwriting an edge, or adding an extra edge?

print(graph.get_edge_data(1, 2))
print(mgraph.get_edge_data(1,2))

which gives the output

>{'weight': 5}
>{0: {'weight': 4.7}, 1: {'weight': 5}}

showing that in the Graph case, the edge attribute gets overwritten (since there is only one edge), but in the MultiDiGraph case a second edge is added with index 1.

Upvotes: 4

Related Questions