简体   繁体   English

从 Python 中的 CSV 文件创建字典

[英]Creating a dictionary from a CSV file in Python

I'm a beginner in python and I'm stuck on my program.我是 python 的初学者,我被困在我的程序上。

I would like to create a program that extracts data from the CSV file and displays the following result when it runs:我想创建一个程序,从 CSV 文件中提取数据并在运行时显示以下结果:

{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)

Here is a screenshot of the 'SpaceMission_data.csv' file.这是“SpaceMission_data.csv”文件的屏幕截图。 屏幕

Leverage the csv module then you can just index the data easily.利用 csv 模块,您可以轻松索引数据。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM