adding networkx edgest with a dictionary

Viewed 90

I have a data structure as follows:

{1: [2, 3, 4, 5, 6, 7, 8, 10, 12], 8: [9], 14: [15, 17, 19, 20]}

the key of the dictionary is the parent and the list following are the children. I would like to add the edges to a Networkx DAG.

I know I can create a list of tuples:

edges=[]
for parent,children in dic.items():
    for child in children:
        edges.append((parent,child))

[(2,1)(3,1)(4,1)  ...etc]

and then add the tuples as:

G.add_edges_from([(2,1)(3,1)(4,1) ....])

Is there any way to more directly add the edges without having to restructure the data structure that I originally have?

thanks

EDIT: This list comprehension does not work properly:

[(parent,child) for child in children for parent,children in dic.items()]
1 Answers

Given that you are creating an undirected graph, use:

import networkx as nx

d = {1: [2, 3, 4, 5, 6, 7, 8, 10, 12], 8: [9], 14: [15, 17, 19, 20]}
G = nx.Graph(d)
edges = list(G.edges)
print(edges)

Output

[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 10), (1, 12), (8, 9), (14, 15), (14, 17), (14, 19), (14, 20)]

Alternative use convert.from_dict_of_lists

import networkx as nx

d = {1: [2, 3, 4, 5, 6, 7, 8, 10, 12], 8: [9], 14: [15, 17, 19, 20]}
G = nx.convert.from_dict_of_lists(d)
edges = list(G.edges)
print(edges)

Output

[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 10), (1, 12), (8, 9), (14, 15), (14, 17), (14, 19), (14, 20)]
Related