Python - Creating a dictionary from external text file -


so file looks this:

0 1 0 2 0 34 0 67 1 98 1 67 1 87 2 23 2 45 2 98 ... 

and on. question is, how can make dictionary text file this:

dict = {'0':['1', '2', '34', '67']         '1':['98', '67', '87']         '2':['23', '45', '98']         '3':['x','x','x']} 

assuming file called test.txt:

from collections import defaultdict import csv   data = defaultdict(list) open("test.txt", "r") f:     reader = csv.reader(f, delimiter=" ")     row in reader:         data[row[0]].append(row[1]) 

then data value be:

{  '0': ['1', '2', '34', '67'],   '1': ['98', '67', '87'],   '2': ['23', '45', '98'],  ... } 

Comments