Graph networkx from python dict

13,174

Solution 1

Suppose you start with

d = {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)}

Then you can use add_nodes_from like this:

g = nx.DiGraph()
g.add_nodes_from(d.keys())

and add_edges_from like this:

for k, v in d.items():
    g.add_edges_from(([(k, t) for t in v]))

Note that there's no need to assume nodes are integers.

Following this, you can see:

>>> g.edges()
[(nan, nan),
 ('AAAD', 'BBDD'),
 ('AAAD', nan),
 ('MMCC', nan),
 ('MMCC', 'AAAD'),
 ('BBDD', nan),
 ('KKLL', 'BBDD'),
 ('KKLL', nan),
 ('KKLL', 'AAFF'),
 ('KKLL', 'AAAD'),
 ('KKLL', 'MMCC'),
 ('AAFF', nan),
 ('AAFF', 'AAAD')]

​

Solution 2

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

g = nx.DiGraph(d)

will return the graph you want.

Share:
13,174
jovicbg
Author by

jovicbg

Updated on June 08, 2022

Comments

  • jovicbg
    jovicbg almost 2 years

    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