hellomynameisA
hellomynameisA

Reputation: 634

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

Upvotes: 0

Views: 179

Answers (2)

LevB
LevB

Reputation: 953

Rather than just printing it out, you can convert it into a dataframe that you can manipulate.

import pandas as pd
a = {(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}}

df = pd.DataFrame(a)
print(df)

Output:

      0  1  0  1  0  1
      0  0  1  1  2  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

Upvotes: 1

azro
azro

Reputation: 54148

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  

Upvotes: 1

Related Questions