3.2.3.1. networkx.Graph.nodes¶
-
Graph.nodes(data=False, default=None)[source]¶ Returns an iterator over the nodes.
Parameters: data : string or bool, optional (default=False)
The node attribute returned in 2-tuple (n,ddict[data]). If True, return entire node attribute dict as (n,ddict). If False, return just the nodes n.
default : value, optional (default=None)
Value used for nodes that dont have the requested attribute. Only relevant if data is not True or False.
Returns: iterator
An iterator over nodes, or (n,d) tuples of node with data. If data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
Notes
If the node data is not required, it is simpler and equivalent to use the expression
for n in G, orlist(G).Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes()) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.node[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}