Reading data from csv file put into dictionary python -


blockquote

help me read csv file. have csv file test8.csv , want read data file , put dict, csv file : 1st row matrices size of value dict create, 2nd row key of dict , next matrix of value of key :

file csv:

1,5  offense involving children  95    96 35 80 100 2,2 battery,theft 173,209    173,224 

output expectation:

dict={['offense involving children']:        [(95,), (96,), (35,), (80,), (100,)],        ['battery', 'theft']:[(173, 209), (173, 224)]} 

this piece of code, , don't have idea continue:

_dir = r'd:\s2\semester 3\tesis\phyton\hasil' open(os.path.join(_dir, 'test8.csv'), 'rb') csv_file: datareader= csv.reader(csv_file, delimiter=' ', quotechar='|') 

that isn't csv file , csv module can't you. in csv file, each line has equal number of columnar fields separated known character such comma. need write own parser data.

this script build dictionary (except uses tuple key because list won't work...)

# todo: write testfile example works open("testfile.txt", "w"). write("""1,5 # matriks size offense involving children # key dictionary 95  # list of value  96 35 80 100 2,2 battery,theft 173,209   # list of tuple value 173,224""")  def strip_comment(line):     return line.split('#', 1)[0].rstrip()  mydict = {}  open("testfile.txt") testfile:     line in testfile:         # first line next record "matrix size"         columns, rows = (int(x) x in strip_comment(line).split(','))         # next line header record         key = tuple(strip_comment(next(testfile)).split(','))         # next lines rows record         vals = [tuple(int(x) x in   strip_comment(next(testfile)).split(','))             _ in range(rows)]         mydict[key] = vals  print(mydict) 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -