Given the two Adjacency List Representation below
g = {
'I': ['J', 'K', 'M'],
'J': ['I', 'K', 'L'],
'K': ['I', 'J', 'M'],
'L': ['J'],
'M': ['I', 'K']
}
#Weighted
g = {
'I': [('J', 1), ('K', 2), ('M', 3)],
'J': [('I', 1), ('K', 7), ('L', 5)],
'K': [('I', 2), ('J', 7), ('M', 6)],
'L': [('J', 5)],
'M': [(I, 3), (K, 6)]
}
How can I output an equivalent adjacency matrix in the form of a list of lists especially for the Weighted Adjacency List. I have applied the algorithm of karakfa from How do I generate an adjacency matrix of a graph from a dictionary in python?. However, I can't seem to implement it to weighted graphs.
keys = sorted(g.keys())
M = [ [0]*len(keys) for i in range(len(keys)) ]
for a,b in [(keys.index(a), keys.index(b)) for a, row in g.items() for b in row]:
M[a][b] = 1
It returns ValueError: ('J', 1) is not in list
IandJin the second list are missing string quotes.