Reputation:
I want every node to have a ipaddress string, latitude and longitude values. Also how do I get a pointer to such object on looking up the graph created by networkx?
Upvotes: 3
Views: 3348
Reputation: 25042
NetworkX is based on the idea that graphs can act like dictionaries. You don't need a custom object to act as nodes, as the nodes can have arbitrary properties added to their "dictionaries".
Consider the following interactive session:
>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_node(1)
>>> G.node[1]['ipaddress'] = '8.8.8.8'
>>> G.node[1]['longitude'] = 37
>>> G.node[1]['latitude'] = 50
>>> G.node[1]
{'latitude': 50, 'ipaddress': '8.8.8.8', 'longitude': 37}
>>> G.node[1]['ipaddress']
'8.8.8.8'
Here, a graph with a single node 1
is created, to which ipaddress
, longitude
, and latitude
are associated. You access that node directly in constant time by asking the graph for the node, and get its properties in much the same way.
To refer to specific nodes, you have a couple of possibilities. You could, e.g., use a dictionary to store a list or set of nodes for any desired properties. The second possibility - which is only useful for a single property that is unique to each node - is to use the property as the node directly. E.g., for IP addresses:
>>> H = nx.Graph()
>>> H.add_node('8.8.8.8', longitude=37, latitude=50)
>>> H.node['8.8.8.8']
{'latitude': 50, 'longitude': 37}
Here, I've also taken advantage of a convenience provided by NetworkX to specify the properties as the node is created.
Upvotes: 5