Search code examples
pythondictionarygraphadjacency-matrix

How can I convert this [['1 0'], ['2 0'], ['3 1 2']] into an adjacency list in python


I have a list of the lists that contain strings, like so :

[['1 0'], 
['2 0'], 
['3 1 2']]  

How can I convert it to an adjacency list in Python please like this: (all ints)

{ 
1: 0, 
2:0, 
3: 1,2 
}

My attempts so far have gotten me to this:

newlist = []
for word in linelist:
    word = word.split(",")
    newlist.append(word)
print(newlist)

which produces this:

[['1 0'], 
 ['2 0'], 
 ['3 1 2']]  

Thanks very much!


Solution

  • You can convert it to a dict with something like this:

    adj_dict = {}
    for inner_list in outer_list:
        values = [int(x) for x in inner_list[0].split()]
        adj_dict[values[0]] = values[1:]