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?