1

How do I create a new node in a nxGraph with either a custom ID, or relabel the ID? The property I'm trying to change is that id label that's set to '0':

graph [
  node [
    id 0
    label "Category:Class-based_Programming_Languages"
  ]

I've tried to do this but it didn't work:

G = nx.Graph()
pageid = 12345
G.add_node('test', id = pageid)

But this does not change the 'id' value, rather, it is just straight-up ignored. The changed id can be seen right there on the Python program, but the problem lies with using write_gml function. It does not change that id value. Does anyone know how I can go about this? Thank you!

Min Park
  • 81
  • 6

1 Answers1

1

Node attributes can be set in the way that you are trying, but if you try to access them with the "compact" node accessor, they are not shown. Various ways are shown below:

import networkx as nx

G = nx.Graph()
pageid = 12345
G.add_node('test', id = pageid)

# the basic node iterator doesn't show the attributes:    
print G.nodes()
>>> ['test']

# but here are some ways to access them:
print G.nodes(data=True)
>>> [('test', {'id': 12345})]

print nx.get_node_attributes(G, "id")
>>> {'test': 12345}

print G.node['test']
>>> {'id': 12345}
Bonlenfum
  • 19,101
  • 2
  • 53
  • 56
  • Yes this is one way to display it, but when you use the function nx.write_gml(G, "test.gml"), the gml file will still show the id value of the node as simply '0'. – Min Park Mar 22 '17 at 00:16
  • I suggest that you add that info to your question! You didn't mention anything about the problem being in `write_gml`. – Bonlenfum Mar 22 '17 at 10:38
  • For me, the code exactly as it is already outputs the node id as defined; however, note that for nodes without the property "id" set, an integer starting from zero is given (see line 360 in [gml.py](https://github.com/networkx/networkx/blob/v1.9.1/networkx/readwrite/gml.py#L360) `nid = G.node[n].get('id',next(count))`) perhaps you are using a different version? I tested with networkx version 1.9.1 and python 2.7.12 – Bonlenfum Mar 22 '17 at 10:44