How to import a text file as a dictionary python

3.8k views Asked by At

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

4

There are 4 answers

2
Justin O Barber On BEST ANSWER

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.

1
K Adamu On
import numpy as np
file_name='text_file.txt'
key_column=0

dat=np.genfromtxt(file_name,dtype=str)
d={i:[] for i in np.unique(dat[:,key_column])}

for row in dat:
    for key in d.keys():
        if row[key_column]==key :d[key].append(row[1])

print d
3
irrelephant On
d = {}
with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
    for line in f:
       (key, val) = line.split()
       if key in d:
           d[key].append(val)
       else:
           d[key] = [val]
for x, v in d.items():
print x, v

Explanation:

Just make the values of d lists, and append to the lists.

0
Hackaholic On

try this:

d = {}
with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
    for line in f:
       (key, val) = line.split()
       if key in d:
           d[key].append(val)
       else:
           d[key] = [val]
for x in d:
    print x,d[x]

if key is found in dictionary it will append the value else create a new pair