1

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

falsetru
  • 357,413
  • 63
  • 732
  • 636
Arslan
  • 27
  • 1
  • 7

4 Answers4

1
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.

irrelephant
  • 4,091
  • 2
  • 25
  • 41
  • awesome, thank you very much it seems it works. The only issue is that I can't find the key 0... How can I extract the print outcome to a txt file so that I can look better and see if the 0 key is there as well? Thanks again. – Arslan Nov 22 '14 at 13:32
  • Please see [this question](http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python). – irrelephant Nov 22 '14 at 13:35
  • @Andrea Sportelli You don't need to print to a file to check if a key is there. Simply add one more line to your code: `print d.get('0')`. – Justin O Barber Nov 22 '14 at 13:42
1

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.

Justin O Barber
  • 11,291
  • 2
  • 40
  • 45
0

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

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0
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
K Adamu
  • 39
  • 2