Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding randomized attributes to graph edges

I’ve tried to add, randomly, one of two values of attribute in a dict, to each edge of some listed graphs, through the following code:

import networkx as nx
import random

Glist = []

for _ in range(12):
    g = nx.erdos_renyi_graph(n = 20, p = random.random())
    Glist.append(g)

for i in range(len(Glist)):
    for u, v in Glist[i].edges():
        attribs = {Glist[i].edges(): {'relation': random.choice(['friend', 'enemy'])}}

def set_Net_att(my_list, my_dict):
    for _ in my_list:
        for i in range(len(my_list)):
            gatt = nx.set_edge_attributes(my_list[i], my_dict)

set_Net_att(Glist, attribs)

print(Glist[2].edges(data = True))

But I got this error:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_14600/893381260.py in <module>
     14 for i in range(len(Glist)):
     15     for u, v in Glist[i].edges():
---> 16         attribs = {Glist[i].edges(): {'relation': random.choice(['friend', 'enemy'])}}
     17 
     18 def set_Net_att(my_list, my_dict):

TypeError: unhashable type: 'EdgeView'

How can I get things done? I’d really appreciate your support.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You do not construct the dictionary for the function set_edge_attributes correctly (and, in general, use too many non-Pythonic features in your code). Here is a correct (and improved) solution:

# Build a list of graphs
glist = [nx.erdos_renyi_graph(n = 20, p = random.random()) for _ in range(12)]

# Generate and assign attributes
for g in glist:
    attribs = {edge: random.choice(['friend', 'enemy']) for edge in g.edges}
    nx.set_edge_attributes(g, attribs, "relation")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading