How to add edges with a list as label in Networkx Python

I have this example:

G.add_nodes_from(List1)
G.add_nodes_from(List2)
edgeList = list(zip(List1, List2))
for item in List3: G.add_edges_from(edgeList, label = item) 

What I want as outcome is each edge between the two lists to have as a label the corresponding element of the list3. Something like this:

(List1[0], List2[0], {'label': List3[0]})

1 Answer

Note: I have change the variable name from List1 to source_nodes, List2 to dest_nodes and List3 to data_nodes in the following code.

You can try to use zip over all three lists and add the edges using nx.add_edge. Something like this:

import networkx as nx
source_nodes = ['A', 'B', 'C', 'D']
dest_nodes = ['P', 'Q', 'R', 'S']
data_nodes = ['W', 'X', 'Y', 'Z']
G = nx.DiGraph()
# Each element of this zip will be
# (source[i], dest[i], data[i])
for u,v,d in zip(source_nodes, dest_nodes, data_nodes): G.add_edge(u, v, label=d)
print(G.edges(data=True))
# OutEdgeDataView([('A', 'P', {'label': 'W'}),
# ('B', 'Q', {'label': 'X'}),
# ('C', 'R', {'label': 'Y'}),
# ('D', 'S', {'label': 'Z'})])

You can also view the code in this Google Colab Notebook for more info.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like