pythondictionarygraphnetworkxedges

Networkx creating a graph from dictionary where dict shows the connections


I have a dictionary, and I would like to create a networkx DiGraph with it. The dictionary shows the downstream nodes:

dict_ = {0: [1],
         1: [],
         2: [],
         3: [0, 1],
         4: [0, 1, 2]}

The important thing, here is (1) and (2) are end nodes, (3) is connected to (1) over (0).

The graph should look like following:

1                2        ^    # digraph directions always to up
|                |        |
0____            |        |
|    |           |        |
3    |           |        |
     |___________|        |
     4                    |

How can I add edges in a way, it would respect my constraints? The algorithm should be somewhat generic, since I have a different dictionary for different situations.


Solution

  • I might have misunderstood the question but wouldn't a simple generator to unnest the list do the trick?

    G = nx.from_edgelist(((n1, n2) for n1, l in dict_.items() for n2 in l),
                         create_using=nx.DiGraph)
    

    Output graph:

    enter image description here

    Or, if the values in the dictionary are a path, maybe:

    from itertools import pairwise
    
    G = nx.from_edgelist(((n1, n2) for k, l in dict_.items()
                          for n1, n2 in pairwise((k, *l))),
                         create_using=nx.DiGraph)
    

    Output:

    enter image description here