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.
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")