Peaceful
Peaceful

Reputation: 5450

get_edge_attribute returns a key error in networkx

I am trying something very simple in networkx

import networkx as nx
G = nx.erdos_renyi_graph(4,1) # This creates a complete graph 

nx.set_edge_attributes(G, 'sign', {(0, 1) : 1})

print nx.get_edge_attributes(G, 'sign')[(0, 1)]

It prints 1. So far so good. But now I change the last line to:

print nx.get_edge_attributes(G, 'sign')[(1, 0)]

I thought that since edges are undirected, this shouldn't matter and the code should again print 1. However, to my surprise, I get this:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print nx.get_edge_attributes(G, 'sign')[(1, 0)]
KeyError: (1, 0)

This is driving me crazy. Shouldn't it treat (1, 0) same as the (0, 1)? Also, if this is not the case, how do I make networkx treat them same? Also, at other places when we talk about edges, do we always need to specify everything for each edge twice?

Thanks in advance for any help.

Upvotes: 1

Views: 2084

Answers (1)

Fabio Lamanna
Fabio Lamanna

Reputation: 21552

I think you should access the edge attribute for Undirected graphs with:

G[0][1]['sign']

and

G[1][0]['sign']

which both correctly return 1. I think that the nx.get_edge_attributes method allows only to get the attribute for the edge as a whole, as:

print nx.get_edge_attributes(G, 'sign')

returns:

{(0, 1): 1}

Hope that helps.

Upvotes: 2

Related Questions