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 nodes and edges to an existing graph in networkx via dictionaries

Do you know how to add nodes and edges to an existing graph using dictionaries?

Let’s say I have a list of nodes l = ['a', 'b', 'c'] and a dictionary d such that d = {'a': ['apple', 'banana'], 'b': ['orange']}.

How can I implement this addition to an existing graph with networkx such that apple and banana will be two different nodes each linked to a and orange will be linked to b?

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

I already have a,b,c connected to a node z.

This is how I create the initial graph

import networkx as nx
from itertools import product

G = nx.from_edgelist(product(l, z), create_using=nx.DiGraph)

How can I modify it?

>Solution :

You need to rework your dictionary:

import networkx as nx
from itertools import product

l = ['a', 'b', 'c']
d = {'a': ['apple', 'banana'], 'b': ['orange']}

G = nx.from_edgelist(product('z', l), create_using=nx.DiGraph)

G.add_edges_from([(n1, n2) for n1, l in d.items() for n2 in l])

Output:

enter image description here

Intermediate list comprehension:

[(n1, n2) for n1, l in d.items() for n2 in l]
# [('a', 'apple'), ('a', 'banana'), ('b', 'orange')]

reversed order

G = nx.from_edgelist(product(l, 'z'), create_using=nx.DiGraph)

G.add_edges_from([(n2, n1) for n1, l in d.items() for n2 in l])

Output:

enter image description here

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