Search code examples
pythontextdictionarygraphedges

How to import a text file as a dictionary python


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


Solution

  • As one other possible option, you can also use defaultdict here:

    from collections import defaultdict
    d = defaultdict(list)
    with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
        for line in f:
            key, val = line.split()
            d[key].append(val)
    for k, v in d.items():
        print(k, v)
    

    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.