Marios
Marios

Reputation: 51

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 dictionary to be of this format :

adjacency_list_dict = {[1]: {[2,3,10], [2]: [1,3]....}etc

NOTICE that despite looking like a directed graph, it actually is undirected and the list-value of each key in the dictionary must contain all the adjacent nodes, for example [10]: [1,4,7] despite 10 not being in the first column in any of the txt file lines.

Right now i am stuck with this code block:

# Main file for assignment 2
input_filename = "example_graph_1.txt"
def create_teams():
    return []
def create_lex():
    return {}
def make_to_list(node):
    return [node]

teams = create_teams()
adjacency_graph = create_lex()

with open(input_filename) as graph_input:
    for line in graph_input:
        nodes = [int(x) for x in line.split()]
        for i in nodes:
            if make_to_list(i) not in teams:
                teams.append(make_to_list(i))
            if i not in adjacency_graph:
                adjacency_graph[i] = create_teams()
    print adjacency_graph
    print teams

Please ignore all other variables, the dictionary adjacency_graph is what i am concerned about. :)

How should i proceed?

Upvotes: 0

Views: 1650

Answers (2)

Neil
Neil

Reputation: 14313

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 = {}

with open("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)

Upvotes: 3

Astrom
Astrom

Reputation: 767

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]}

Upvotes: 1

Related Questions