I have an input text file which contains distance between 2 cities shown below
Luebeck Hamburg 63
Hamburg Bremen 116
Hamburg Hannover 153
Hamburg Berlin 291
Bremen Hannover 132
Bremen Dortmund 234
Hannover Magdeburg 148
Hannover Kassel 165
Magdeburg Berlin 166
Berlin Dresden 204
Dresden Leipzig 119
Leipzig Magdeburg 125
Dortmund Duesseldorf 69
Kassel Frankfurt 185
Frankfurt Dortmund 221
Frankfurt Nuremberg 222
Leipzig Nuremberg 263
Dortmund Saarbruecken 350
Saarbruecken Frankfurt 177
Saarbruecken Karlsruhe 143
Karlsruhe Stuttgart 71
Stuttgart Frankfurt 200
Stuttgart Munich 215
Stuttgart Nuremberg 207
Nuremberg Munich 171
Manchester Birmingham 84
Birmingham Bristol 85
Birmingham London 117
END OF INPUT
My dictionary should be like this:
{
'luebeck': [('hamburg', '63')], 'dortmund': [('bremen', '234'), ('duesseldorf', '69')]
'saarbruecken': [('dortmund', '350'), ('frankfurt', '177'), ('karlsruhe', '143')]
..
}
My code is working but it is not efficient and I want to optimize it:
def read_file(filename):
paths = []
graph = {}
f = open(filename, 'r')
for line in f:
route = line.lower().split()
paths.append(route)
# to remove space and end of input
del paths[-1]
del paths[-1]
for path in paths:
node = path[0]
if node not in graph:
graph[node] = {}
graph[node][path[1]] = int(path[2])
elif node in path:
graph[node][path[1]] = int(path[2])
node = path[1]
if node not in graph:
graph[node] = {}
node = path[1]
if node not in graph:
graph[node] = {}
graph[node][path[0]] = int(path[2])
elif node in path:
graph[node][path[0]] = int(path[2])
return graph
Please tell me if any additional information is required.