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
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}})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments