python3,将csv转换成Python字典

2024-04-27 05:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取一个csv文件(可以在我的GitHub repo上找到,https://github.com/playdscription/100daysofpython/blob/master/day_012/master_exercise_boolean.csv),并将其转换为python3中的字典。我们的想法是使用google表单,让多人填写,然后将其转换为csv,并将python脚本打包到字典中,这样我就可以通过各种方式访问这些信息。你知道吗

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

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]

Tags: ofcsvtheinmasteractionsforif
2条回答

也许不是你想要的,但这是你应该做的。你知道吗

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)

您需要做的是创建键名,然后将值赋给dictionary。此外,项被读取为字符串“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

相关问题 更多 >