I have a text file of the looks like this:
0 1
0 2
0 3
2 3
3 4
4 1
.. ..
I'd like to make it a dictionary looking like this
graph = { "0" : ["1", "2", "3"],
"1" : ["4", "0"],
"2" : ["0", "1", "3"],
"3" : ["0", "2", "4"],
"4" : ["1", "3"]
}
the file text list is a list of edges for a graph. I need to make a graph out of it without using any package. My final aim is to calculate the diameter and clustering coefficient. However, before starting I need to create the graph.
My attempt so far was:
d = {}
with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
for x in d:
print (x)
Outcome:
471
472
474
475
476
477
478
479
480
481
483
484
485
486
487
Thanks
As one other possible option, you can also use
defaultdict
here:This saves you from having to check whether a key is already in
d
or not, and it also saves you a couple of lines.