Skip to content Skip to sidebar Skip to footer

How To Read Txt File And Create Dictionary With Adjacency List Python

I am trying to create an adjacency list dictionary in python by reading a .txt file with this format: 1 2 1 3 1 10 2 3 4 5 4 6 4 10 5 6 7 8 7 9 7 10 8 9 I want the resulting dicti

Solution 1:

You can do this by using .setdefault and split. Basically, the code will create a new list at key parts[0], if it's not defined. After that, we append to the list.

di = {}

withopen("file.txt", "r") as fi:
    for line in fi:
        parts = line.split()
        di.setdefault(parts[0],[]).append(parts[1])

print(di)

And the easiest way to make it bidirectional is to append the dictionary both ways:

di = {}

with open("file.txt", "r") as fi:
    for line in fi:
        parts = line.split()
        di.setdefault(parts[0],[]).append(parts[1])
        di.setdefault(parts[1],[]).append(parts[0])

print(di)

Solution 2:

import numpy

l1, l2  = numpy.genfromtxt('t.txt', dtype='float').T 
uniques = list(numpy.unique(l1))+list(numpy.unique(l2))    
dic = {}

for i in numpy.unique(uniques):
    a =list(l2[numpy.where(l1 == i)[0]])
    b =list(l1[numpy.where(l2 == i)[0]])

    c = list(numpy.unique(a+b))
    dic[i] = c

output: {1.0: [2.0, 3.0, 10.0], 2.0: [1.0, 3.0], 3.0: [1.0, 2.0], 4.0: [5.0, 6.0, 10.0], 5.0: [4.0, 6.0], 6.0: [4.0, 5.0], 7.0: [8.0, 9.0, 10.0], 8.0: [7.0, 9.0], 9.0: [7.0, 8.0], 10.0: [1.0, 4.0, 7.0]}

Post a Comment for "How To Read Txt File And Create Dictionary With Adjacency List Python"