Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph networkx from python dict

I need help with networkX or any other graph lib in python. I have dictionary with keys and for every key a few value:

{nan: array([nan, nan, nan, nan, nan, nan, nan], dtype=object),
 'BBDD': array([nan, nan, nan, nan, nan, nan, nan], dtype=object),
 'AAAD': array(['BBDD', nan, nan, nan, nan, nan, nan], dtype=object),
 'AAFF': array(['AAAD', nan, nan, nan, nan, nan, nan], dtype=object),
 'MMCC': array(['AAAD', nan, nan, nan, nan, nan, nan], dtype=object),
 'KKLL': array(['AAFF', 'MMCC', 'AAAD', 'BBDD', nan, nan, nan], dtype=object),
 'GGHH': array(['KKLL', 'NI4146', 'MMCC', nan, nan, nan, nan],dtype=object), ...}

Now my question is, how can I put data from this dict to graph, where keys would be nodes and values would be edges. Which way is the best for iteration through dict?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)

nx.draw(g,with_labels=True)
plt.draw()
plt.show()

It should be something like this, but with other data

like image 581
jovicbg Avatar asked Jun 14 '17 09:06

jovicbg


1 Answers

Actually, the Graph can simply be initialized by a dictionary. In this case:

g = nx.DiGraph(d)

will return the graph you want.

like image 170
CrnlWes Avatar answered Sep 19 '22 09:09

CrnlWes