I'm looking for an simple way of modifying the value of a single attribute of a single node inside a NetworkX Graph.
The NetworkX documentation only mentions a function for setting an attribute for all nodes in the graph, e.g.:
nx.set_node_attributes(G, bb, 'betweenness')
This might be appropriate in many situations in which such such an attribute is easy to calculate for all nodes in a graph (like be mentioned betweenness). Likewise, there is an easy way to access single node attributes in NetworkX:
graph.nodes[nodeName][attribute]
However, the attributes accessed this way are read-only.
So what i'm looking for a way to set attributes as simple as reading.
Thanks in advance.
In your example, bb
is a dict whose keys are the nodes. You don't need the dict to have a key for all nodes in the graph, just the nodes for which you want to define the attribute. In the example below, I create a graph, and then set the 'weight'
of node 0
to be 5
and of node 3
to be 2
. This leaves the attributes for the other nodes unaffected, so since they've never been created, they don't exist.
import networkx as nx
G = nx.fast_gnp_random_graph(10,0.2)
nx.set_node_attributes(G, {0:5, 3:2}, 'weight')
G.nodes[0]['weight']
> 5
G.nodes[3]['weight']
> 2
G.nodes[1]['weight']
> KeyError: 'weight'
So we set the weight for 0
and 3
but not any of the others. You could also set more than one attribute at once, but that requires a slightly different call. Here we have
nx.set_node_attributes(G, {1:{'weight':-1, 'volume':4}})
G.nodes[1]['weight']
> -1
G.nodes[1]['volume']
> 4
Just to see what the attributes look like after all of that:
G.nodes(data=True)
> NodeDataView({0: {'weight': 5}, 1: {'weight': -1, 'volume': 4}, 2: {}, 3: {'weight': 2}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}, 9: {}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With