I'm a beginner in python and I'm stuck on my program.
I would like to create a program that extracts data from the CSV file and displays the following result when it runs:
{company: [total number of missions, number of successful missions, number of failed missions]}
I started to write a code but I think I made mistakes. Can someone help me with this program?
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)
Leverage the csv module then you can just index the data easily. Check if the key is there if it is just access the last entry otherwise add a new list.
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
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.