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?
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:
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:

