我正在尝试获取csv文件(可以在我的GitHub存储库https://github.com/playdscription/100daysofpython/blob/master/day_012/master_exercise_boolean.csv中找到),并将其转换为python3中的字典。我们的想法是拿一张google工作表,让多个人填写它,然后将它转换为csv,并将python脚本打包到字典中,这样我就可以通过各种方式访问这些信息。
我打开csv文件,创建一个读取器对象,然后遍历每一行,并遍历该行特定部分中的每一项,如果该项中有值,那么我希望它将该值写入我标记为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]
发布于 2018-03-19 12:22:08
您需要做的是创建键名称,然后将值分配给字典。此外,项被读取为字符串'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
发布于 2018-03-19 12:35:16
这可能不是你想要的,但这是你应该做的。
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)
https://stackoverflow.com/questions/49355577
复制相似问题