Reputation: 107
I found few advice in this site regarding how to convert a list into a dictionary. I have successfully followed it. But i got struck in performing a conversion from a list to dictionary of dictionary; like graph representation
I/p: 0,0,1,1,0,4
o/p: 0:{1:0,2:1}---------------------->1:0 means 1 is vertex and 0 is weight
1:{0:1,2:4}
Here, keys represent the vertices of graph.
Can you please advice me, how to resole this issue?
THank you
Upvotes: 0
Views: 737
Reputation: 3913
First, you need to represent the graph differently. The user input should be a matrix.
Item (i,j) in the matrix should be X if there's an edge weighted X from vertex i to vertex j, and be (let's say) "-1" if there isn't. (This is all interchangeable of course).
0 1 2
0 -1 0 1
1 1 -1 4
2 1 4 -1
So the input string should be like:
-1,0,1;1,-1,4;1,4,-1
Afterwards, use collections.defaultdict
(documentation) like so:
>>> d = defaultdict(dict)
>>> input = '-1,0,1;1,-1,4;1,4,-1'
>>> lst = map(lambda x: map(lambda y: int(y), x.split(',')), input.split(';'))
>>> for i,j in enumerate(lst):
... for k,l in enumerate(j):
... d[i][k] = l
...
>>> d
defaultdict(<type 'dict'>, {0: {0: -1, 1: 0, 2: 1}, 1: {0: 1, 1: -1, 2: 4}, 2: {
0: 1, 1: 4, 2: -1}})
Upvotes: 2
Reputation: 168626
I convert alredy the list into a matrix form of [[0 1 2],[1 0 3],[2 2 0]] it gives me the row length,column length.But I again got struck how to do this dictionary prsentation
mx = [[0, 1, 2],[1, 0, 3],[2, 2, 0]]
md = { i:
{ j:v for (j,v) in enumerate(sublist) if i != j }
for (i,sublist) in enumerate(mx)
}
print (md)
Upvotes: 2