Search code examples
pythondictionarynetworkxadjacency-matrix

print matrix from dictionary


I would like to print adjacency matrix from a dictionary I got from Floyd-Marshall algorithm in network-x. How can I do it? I came up with this to see the dictionary as it is:

X = nx.floyd_warshall(gra)
Y = {a: dict(b) for a, b in X.items()}
print(Y)

and it returns this:

{(0, 0): {(0, 0): 0, (1, 0): 1, (0, 1): 1, (1, 1): 2, (0, 2): 2, (1, 2): 3}, (1, 0): {(1, 0): 0, (0, 0): 1, (1, 1): 1, (0, 1): 2, (0, 2): 3, (1, 2): 2}, (0, 1): {(0, 1): 0, (0, 0): 1, (1, 1): 1, (0, 2): 1, (1, 0): 2, (1, 2): 2}, (1, 1): {(1, 1): 0, (1, 0): 1, (0, 1): 1, (1, 2): 1, (0, 0): 2, (0, 2): 2}, (0, 2): {(0, 2): 0, (0, 1): 1, (1, 2): 1, (0, 0): 2, (1, 0): 3, (1, 1): 2}, (1, 2): {(1, 2): 0, (1, 1): 1, (0, 2): 1, (0, 0): 3, (1, 0): 2, (0, 1): 2}}

Is it possible to memorize in a variable and then print the adjacency matrix?

sample output:

       (0,0)  (0,1)   (1,0)  ...
(0,0)    0      1      2      1   ...
(0,1)    1      0      1 
...
(1, 2)   7      6     ...

Thanks


Solution

  • A pretty simple idea would be to print the header row which are the keys, then for each pair key/mappings print the values by using the header key to be sure to get the good order

    keys = vals.keys()
    print("       ", *keys)
    for k, v in vals.items():
        print(k, ("{:^7}" * len(keys)).format(*(v[k] for k in keys)))
    
            (0, 0) (1, 0) (0, 1) (1, 1) (0, 2) (1, 2)
    (0, 0)    0      1      1      2      2      3   
    (1, 0)    1      0      2      1      3      2   
    (0, 1)    1      2      0      1      1      2   
    (1, 1)    2      1      1      0      2      1   
    (0, 2)    2      3      1      2      0      1   
    (1, 2)    3      2      2      1      1      0