5

I am trying to generate a graph of cities from a file. Each readline() I am getting three values, a, b, and c. a and b are strings, names of cities, and c is an int, the path cost between a and b. How can I store a,b,c so that I get something like

graph = {
          'a1': {'b1': c1, 'b1': 5, 'a2': c2},
          'a2': {'a1': c2},
          'b1': {'a1': c1},
        }

Here is part of my code:

dict = dict()   #dictionary for storing values
while (True):
    new_path = file.readline()
    if new_path == "":
        break
    new_path = new_path.rstrip().split(", ")
    a = new_path[0][2:len(new_path[0]) - 1] #start town
    b = new_path[1][1:len(new_path[1]) - 1] #end town
    c = new_path[2][0:len(new_path[2]) - 1] #path cost
    print(a+" "+b+" "+c)   #this prints Arlington Chelmsford 4

....... Since I don't know if the key is already in the dictionary, I have tried adding the key with empty value if key is not in dict.keys(), but then update() will function weirdly and give me some sort of list. I am new to python so please explain to me how to create such a graph that doesn't include any [] symbol in. Thanks a million!!

the final result I want would be something like this:

{'Arlington': {'Chelmsford': 4, 'Berkshire': 10}, 'Chelmsford': {'Arlington': 4, 'Berkshire': 5}, 'Berkshire': {'Arlington': 10, 'Chelmsford': 5}}

blhsing
  • 91,368
  • 6
  • 71
  • 106
Biying Zhang
  • 53
  • 1
  • 5

2 Answers2

3

You can use the following loop that sets the graph dict in both directions:

graph = {}
for line in file:
    a, b, c = line.rstrip().split(', ')
    graph.setdefault(a, {})[b] = c
    graph.setdefault(b, {})[a] = c

so that given file content:

Arlington, Chelmsford, 4
Arlington, Berkshire, 10
Chelmsford, Berkshire, 5

graph would become:

{'Arlington': {'Chelmsford': '4', 'Berkshire': '10'}, 'Chelmsford': {'Arlington': '4', 'Berkshire': '5'}, 'Berkshire': {'Arlington': '10', 'Chelmsford': '5'}}

blhsing
  • 91,368
  • 6
  • 71
  • 106
1

Here's a example leveraging the built-in libraries. defaultdict makes sure if a key is not already present in the dictionary it is created with default value...in this case, an empty dictionary. The csv module can be used to read and parse comma-separated input.

from collections import defaultdict
import csv

D = defaultdict(dict)

with open('input.csv',newline='') as f:
    r = csv.reader(f)
    for a,b,c in r:
        D[a][b] = int(c)
        D[b][a] = int(c)

print(dict(D)) # dict() is unnecessary, but prints better than the defaultdict object

Input:

Arlington,Chelmsford,4
Arlington,Berkshire,10
Chelmsford,Berkshire,5

Output:

{'Arlington': {'Chelmsford': 4, 'Berkshire': 10}, 'Chelmsford': {'Arlington': 4, 'Berkshire': 5}, 'Berkshire': {'Arlington': 10, 'Chelmsford': 5}}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251