Python 3,将csv转换为python字典

时间:2018-03-19 03:55:29

标签: python csv dictionary

我正在尝试使用一个csv文件(可以在我的GitHub repo上找到https://github.com/playdscription/100daysofpython/blob/master/day_012/master_exercise_boolean.csv并将其转换为python3中的字典。想法是拿一张google工作表,有多个人填写它out,然后将其转换为csv并将python脚本包放入字典中,以便我可以通过各种方式访问​​此信息。

我打开csv文件,从中创建一个reader对象,然后循环遍历每一行,并循环遍历该行的特定部分中的每个项目,如果该项目中有值,那么我希望它将该值写入我标记为关节的字典。但是,即使项目中有值,我也无法将其打印到该值。我做错了什么?

import csv

exercise_library = {}

joint = {}


with open('/Users/laptop/github/100daysofpython/day_012/master_exercise_boolean.csv' , 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    #look for joint actions of the NECK
    for line in csv_reader:
        for item in line[4:7]:
            if item == True:
                joint[line[3]] = [item]
    #look for joint actions of the scapula.
        for item in line[8:12]:
            if item == True:
                joint[line[7]] = [item]
    #look for joint actions of the glenero_humeral.
        for item in line[13:19]:
            if item == True:
                print(item)
                #joint[line[12]] = [item]

        exercise_library[line[0]] = [joint]

2 个答案:

答案 0 :(得分:0)

您需要做的是创建密钥名称,然后将值分配给字典。此外,项目被读作字符串'1'而不是布尔值,所以我在下面的代码中更改了它。

import csv

exercise_library = {}

joint = {}

colnames = []


with open('test.csv' , 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    counter = 0
    for line in csv_reader:
        if counter==0:
            colnames.append(line[3])
            colnames.append(line[7])
            colnames.append(line[12])
        else:
            for item in line[4:7]:
                if item == '1':
                    joint[colnames[0]] = item
            #look for joint actions of the scapula.
            for item in line[8:12]:
                if item == '1':
                    joint[colnames[1]] = item
            #look for joint actions of the glenero_humeral.
            for item in line[13:19]:
                if item == '1':
                    joint[colnames[2]] = item

            exercise_library[line[0]] = joint
        counter = counter + 1

答案 1 :(得分:0)

可能不是你想要的,但这是你应该做的。

import csv
import requests
from collections import defaultdict

header = []
data = defaultdict(list)
with open('master_exercise_boolean.csv') as csv_file:
    csv_reader = csv.reader(csv_file)
    for i, line in enumerate(csv_reader):
        if i ==0:
            header = line
        else:
            for j, item in enumerate(line):
                if item:
                    data[header[j]].append(item)

print(data)