简体   繁体   中英

Read CSV file as a dictionary containing first row as headers (keys)

I am trying to read a CSV file which contains a number of columns and dump the array into a dictionary. First row would be a key of dictionary, and the rest of the rows are list (values of key). I tried the following but I have loads of columns which may vary.

reader = csv.reader(open('CSV/Logger_data.csv', 'r'))
d = {}
for key,value in reader:
    d[key] = value

DictReader seems to work but when I print through iterating but how can I store the data in a dictionary reader . This is what I tried so far:

with open ('CSV/Logger_data.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row["DateTime"], row["Column1"])
import csv
from itertools import chain

def get_mulList(*args):
    return map(list,zip(*args))

csv_data = open('logger_data.csv','r')
data = list(csv.reader(csv_data))
ind_dict = dict(zip(data[0],get_mulList(*data[1:])))    
print ind_dict

if your CSV is like this,

'DateTime'  'Column1'
 1-2-2012    a
 2-3-2013    b
 3-4-2014    c 

from the above script you will get output like this,

{ 
  'DateTime':['1-2-2012','2-3-2013','3-4-2014'],
  'Column1':['a','b','c']
}

Here is an example:

import csv

d={}
with open("logger_data.csv","r") as csvf:
    content = csv.reader(csvf, delimiter=";")
    for row in content:
        if not row[0] in d:
            d[row[0]]=[]
        for value in row[1:]:
            d[row[0]].append(value);

For the csv file "logger_data.csv" looking like this:

ab;123;234;345

ce;1;2;3;4

ll;99;12;123;4;5

Output:

{'ab': ['123', '234', '345'],
 'ce': ['1', '2', '3', '4'],
 'll': ['99', '12', '123', '4', '5']}

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