set_node_attributes

set_node_attributes(G, name, values)[source]

Sets node attributes from a given value or dictionary of values.

Parameters:
  • G (NetworkX Graph)
  • name (string) – Name of the node attribute to set.
  • values (dict) – Dictionary of attribute values keyed by node. If values is not a dictionary, then it is treated as a single attribute value that is then applied to every node in G. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the node attribute for each node.

Examples

After computing some property of the nodes of a graph, you may want to assign a node attribute to store the value of that property for each node:

>>> G = nx.path_graph(3)
>>> bb = nx.betweenness_centrality(G)  # this is a dictionary
>>> nx.set_node_attributes(G, 'betweenness', bb)
>>> G.node[1]['betweenness']
1.0

If you provide a list as the third argument, updates to the list will be reflected in the node attribute for each node:

>>> labels = []
>>> nx.set_node_attributes(G, 'labels', labels)
>>> labels.append('foo')
>>> G.node[0]['labels']
['foo']
>>> G.node[1]['labels']
['foo']
>>> G.node[2]['labels']
['foo']