Skip to content Skip to sidebar Skip to footer

How Do I Generate An Adjacency Matrix Of A Graph From A Dictionary In Python?

I have the following dictionary: g = { 'A': ['A', 'B', 'C'], 'B': ['A', 'C', 'E'], 'C': ['A', 'B', 'D'], 'D': ['C','E'], 'E': ['B','D'] } It implements a graph, each list contai

Solution 1:

Here is a solution using pandas.

import pandas as pd

g = {
'A': [ 'A', 'B', 'C'], 
'B': [ 'A', 'C', 'E'], 
'C': [ 'A', 'B ',' D '], # I added a comma here'D': [' C ',' E '],
'E': [' B ',' D ']
}

# clean up the example
g = {k: [v.strip() for v in vs] for k, vs in g.items()}

edges = [(a, b) for a, bs in g.items() for b in bs]

df = pd.DataFrame(edges)

adj_matrix = pd.crosstab(df[0], df[1])

# 1  A  B  C  D  E# 0               # A  1  1  1  0  0# B  1  0  1  0  1# C  1  1  0  1  0# D  0  0  1  0  1# E  0  1  0  1  0

I am not sure why you have 2 in your example matrix in (A, A) position.

Solution 2:

without pandas

keys=sorted(g.keys())
size=len(keys)

M = [ [0]*size for i inrange(size) ]

for a,b in [(keys.index(a), keys.index(b)) for a, row in g.items() for b in row]:
     M[a][b] = 2if (a==b) else1

M

[2, 1, 1, 0, 0],
[1, 0, 1, 0, 1],
[1, 1, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 1, 0, 1, 0]]

Explanation

for a, row in g.items() iterates over the key:value entries in dictionary, and for b in row iterates over the values. If we used (a,b), this would have given us all the pairs.

(keys.index(a), keys.index(b)) But we need the index to assign to the corresponding matrix entry,

keys=sorted(g.keys()) that's why we extracted and sorted the keys.

for a,b in... getting the index entries and assigning value 1 or 2 based on diagonal element or not.

M = [ [0]*size for ... matrix cannot be used before initialization.

Solution 3:

import numpy as np
mat = np.zeros(shape = (len(g), len(g)))
for k, vs in g.items():
    for v in vs:
        if v in g[k]:
            mat[k][v] = 1

Post a Comment for "How Do I Generate An Adjacency Matrix Of A Graph From A Dictionary In Python?"