0
votes

I want to sample three edge attributes from a directed graph I built with networkX. The edges in the graph with the attribute 'dependency' are listed below:

import networkx as nx
import random
from random import choice
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)

Now I want to sample three different edge attributes from above and multiply them with a random number between 0 and 1. It should look somehow like this:

for i in range(3):
    sampled_edge = random.sample(G.edges, 1)
    sampled_edge_with_random_number = sampled_edge['dependency'] * random.uniform(0,1)
    print(sampled_edge_with_random_number)

But I keep getting the following error message:

TypeError: list indices must be integers or slices, not str

What is the best way to do this?

1
random.sample works only if you import random - mathfux

1 Answers

1
votes

There were two mistakes in your script.

  1. What is random.sample(G.edges, 1)? Definitely it's list that contains one item therefore it can't be a key for any edge. Correct key is sampled_edge[0]
  2. What is sampled_edge? If it's list or tuple, it can't have any keys. The only thing that should have a key is EdgeView of your graph. It should be G.edges then.

After you identify some edge, you can access its atributes too. So just replace your sampled_edge['dependency'] with G.edges[sampled_edge[0]]['dependency'] in your script and that's it.