Rich Rich - 4 months ago 12
Python Question

NetworkX tutorial gives key error over value selection

I'm working through a networkX tutorial, and page nine is this:

>>> g = nx . Graph ()
>>> g . add_node (1 , name = ‘ Obrian ’)
>>> g . add_nodes_from ([2] , name = ‘ Quintana ’ ])
>>> g [1][ ‘ name ’]
‘ Obrian ’


Which I reconstructed in code:

import networkx as nx

g = nx.Graph()

g.add_node(1,name='Obrian')
g.add_nodes_from([2],name='Quintana')

print "Node 1 name: " + g[1]['name']


And yet, for some reason, this simple 5-line script dosn't run:

Traceback (most recent call last):
File "NetTest[nx_tut]--[P09].py", line 9, in <module>
print "Node 1 name: " + g[1]['name']
KeyError: 'name'


I feel like I'm missing something really obvious. What is it?

Answer

You need to access the node property of the graph explicitly. That is, replace g[1]['name'] with g.node[1]['name']

You may be working from an out-of-date tutorial.