简体   繁体   中英

In Python how can I create and organized dictionary through the process of reading a CSV file

I am attempting to read a CSV file into Python and create and organized dictionary from the data retrieved. The CSV has a similar format to the one shown below.

Time  A   B   C   D
 0    1   2   4   5
.1    3   3   5   7
.2    4   5   7   9

When complete I would like the dictionary to look something like this Dict = {'0':[1 2 3 4], '.1':[3 3 5 7], '.2':[4 5 7 9]}

The code below is all I can think to do up to this point. It is not giving me the corret dictionary. I am new to python so any help I can get is greatly appreciated!

import csv
counter = 0
inp = open('Nodal_Quardnets.csv', 'rb')

Xcoord = {}
k = []
v = []

for line in inp.readlines():
    sd = line.strip().split(',')

    for value in range(len(sd)):
        if counter == 0:
            k.append(sd)
            counter = counter + 1
        else:
            v.append(sd)

    Xcoord = dict(zip(k,v))
d = dict()
with open('Nodal_Quardnets.csv', 'r') as f:
    f.readline()    # disregard headers
    for line in f:
        values = [s.strip() for s in line.split(',')]
        d[values[0]] = map(int,values[1:])   # convert list values to int
print d

Output

{'0': [1, 2, 4, 5],
 '.2': [4, 5, 7, 9],
 '.1': [3, 3, 5, 7]}
import csv

def readData(infilepath):
    answer = {}
    with open(infilepath) as infile:
        for line in csv.reader(infile, delimiter='\t'):
            k = int(line[0].lstrip('.'))
            vals = [int(i) for i in line[1:]]
            answer[k] = vals
    return answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM