>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_path(['a','b','c','d'])
>>> G.add_node('d', time='5pm')
How do I call a *single* node, plus its data, by name? I essentially
am looking for the equivalent of G.get_edge_data, but for nodes.
I can get the information by calling the item in the list:
>>> G.nodes(data=True)[3]
('d', {'time': '5pm'})
But I don't know how to get it by calling it by name (e.g. 'd'). I
can get the nodes connected to it by calling:
>>> G['d']
{'c': {}}
But that doesn't seem to provide any node data. I can only think of
iterating over the entire graph using G.nodes_iter(), but that seems
inefficient.
I've also seen code that uses dictionaries as follows:
>>> G.time = {}
>>> G.time['d'] = '6pm'
>>> G.time['d']
'6pm'
Is this still a preferred way to track node (and edge) information? I
was getting the feeling networkX was migrating away from this
approach. Is this correct?
I apologize in advance if there is an obvious and easy solution to
this that I am just missing.
cheers,
Tim
>>> nodeDict = dict(G.nodes(data=True))
>>> nodeDict['d']
{'time': '5pm'}
I'll use this approach for now...
Tim
Actually it's simpler. You can access the node data dictionary directly:
In [1]: import networkx
In [2]: G=networkx.Graph()
In [3]: G.add_node(1,time='5pm')
In [4]: G.node[1]
Out[4]: {'time': '5pm'}
This works the same for edges with G.edge[u][v] which
is the same as G[u][v]
n [5]: G.add_edge(1,2,amount=7)
In [6]: G.edge[1][2]
Out[6]: {'amount': 7}
In [7]: G[1][2]
Out[7]: {'amount': 7}
Aric
Thanks so much, everyone!
Tim
Richard is right - but you can access the node data dictionary directly too.
(Note that add_nodes_from() below with node,attr pairs is new with
networkx-1.1).
In [1]: import networkx
In [2]: G=networkx.Graph()
In [3]: G.add_nodes_from([('a', {}), ('c', {}), ('b', {}), ('d',
{'time': '5pm'})])
In [4]: G.node
Out[4]: {'a': {}, 'b': {}, 'c': {}, 'd': {'time': '5pm'}}
In [5]: G.nodes(data=True)
Out[5]: [('a', {}), ('c', {}), ('b', {}), ('d', {'time': '5pm'})]
Aric
> --
> You received this message because you are subscribed to the Google
> Groups "networkx-discuss" group.
> To post to this group, send email to networkx-
> dis...@googlegroups.com.
> To unsubscribe from this group, send email to networkx-discuss
> +unsub...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/
> group/networkx-discuss?hl=en.