[英]Creating a dictionary from a CSV file in Python
我是 python 的初学者,我被困在我的程序上。
我想创建一个程序,从 CSV 文件中提取数据并在运行时显示以下结果:
{公司:[任务总数,成功任务数,失败任务数]}
我开始编写代码,但我认为我犯了错误。 有人可以帮我完成这个程序吗?
with open ('data-files/SpaceMission_data.csv', 'r') as handle:
content = csv.reader(handle)
print(content)
-------------------------------------------------(new cell)----------------------------------------
import csv
def space_statistics(filename):
'''The function returns a dictionary in which it counts the number of mission for each company in charge
and also counts the number of successful and failed missions'''
space = dict()
err_Msg = 'Error: Check the file path or content'
# TYPE YOUR CODE HERE.
try:
with open(filename, 'r') as handle:
for line in handle:
val = line.split(",")[1:7]
print(val)
space[val[1]] = int(val[7])
print(msg.format(val[1], val[7]))
return space
except:
print("Error: Something wrong with your file location?")
return
help(space_statistics)
利用 csv 模块,您可以轻松索引数据。 检查密钥是否存在,如果它只是访问最后一个条目,否则添加一个新列表。
import csv
def space_statistics(csvFile):
space = {}
with open(csvFile, newline='') as inFile:
reader = csv.reader(inFile)
data = list(reader)
for entry in data[1:]:#skip the first one because thats the header
if entry[2] in space:#company already exists in dict
if entry[-1] == 'Success'
space[entry[2]][1] += 1
else:#failed
space[entry[2]][2] += 1
space[entry[2]][0] += 1#total mission count
else:
space[entry[2]] = [1,0,0]
if entry[-1] == 'Success'
space[entry[2]][1] += 1
else:#failed
space[entry[2]][2] += 1
return space
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.