Skip to content
Advertisement

Networkx: Update single attribute of all nodes within a graph without for loop

I have some code that can update a graph‘s attribute:

JavaScript

This doesn’t update the node attribute, and instead applies the update to the graph as a separate entity. Is there any way to mass-update a single attribute of an entire set of nodes without sticking in for node in (range(0, len(graph.nodes)): graph.nodes[node]['test_attribute'] = <new_value> somewhere?

Edit: I should’ve clarified that the reason I’m unhappy with this iteration over the graph’s contents is that this initial value needs to be reset for all nodes prior to the running of a second loop after this that calls into question the value of the attribute and follows different logical paths based on that. So I’m hoping to avoid iterating over all nodes twice, albeit this first loop is much less computationally intensive and hopefully unnecessary.

Advertisement

Answer

If you want to set the attribute for all nodes to the same value, you can use graph.add_nodes_from(graph.nodes,attribute_name='attribute_value')

This updates the provided attribute (adds the node and attribute if non-existent) but maintains any other node attributes and edges you already have in the graph. See the example below:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement