Reputation: 105
I have the following graph with the edge attributes:
import networkx as nx
import random
G=nx.DiGraph()
G.add_edge('x','a', dependency=0.4)
G.add_edge('x','b', dependency=0.6)
G.add_edge('a','c', dependency=1)
G.add_edge('b','c', dependency=0.3)
G.add_edge('b','d', dependency=0.7)
G.add_edge('d','e', dependency=1)
G.add_edge('c','y', dependency=1)
G.add_edge('e','y', dependency=1)
After setting the structure of my graph, I will sample three different edge attributes and multiply them with a random number as followed:
for i in range(3):
sampled_edge = random.sample(G.edges, 1)
print(sampled_edge)
sampled_edge_with_random_number = G.edges[sampled_edge[0]]['dependency'] * random.uniform(0,1)
print(sampled_edge_with_random_number)
Now I want to update the initial graph attribute with the new sampled graph attribute so it would look something like this. The algorithm should look for the same edge attribute in the structure and update the dependency value:
for i in G.edges:
if i == sampled_edge:
i['dependency'] = sampled_edge_with_random_number
Can someone help me with this?
Upvotes: 3
Views: 5483
Reputation: 11949
You can just access the attribute to update and change it
>>> G=nx.DiGraph()
>>> G.add_edge('x','a', dependency=0.4)
>>> G['x']['a']
{'dependency': 0.4}
>>> G['x']['a']['dependency'] = 10
>>> G['x']['a']
{'dependency': 10}
Another approach is nx.set_edge_attributes
>>> sampled_edge = ('x', 'a')
>>> new_val = 42
>>> nx.set_edge_attributes(G, {sampled_edge:{'dependency':new_val}})
>>> G['x']['a']['dependency']
42
where ('x','a')
is your sampled_edge
.
Upvotes: 10