使用csv文件中的行号创建字典[Python] [英] Create a dictionary using the row number in a csv file [Python]

查看:141
本文介绍了使用csv文件中的行号创建字典[Python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,其中包含60位参与者的调查数据.第一列是参与者的号码,每个号码对应从该参与者收集的所有数据.看起来像这样:

I have a CSV file containing survey data on 60 participants. The first column is the participant's number, and for each number corresponds all the data collected from that participants. It looks something like:

参与者人数:1,性别:女性,学习水平:研究生毕业

Participant number: 1, Gender: Female, Level of study: Postgrad

我想创建一个字典,其中的键是参与者编号,值是包含所有数据的整个行,以具有以下内容:

I would like to create a dictionary where the key is the Participant Number and the value is the whole of the row with all the data, to have something like this:

{1:女性,研究生,美国人,是,否,否,是,是,否...},依此类推.我仍然是新手,到目前为止,这是我尝试过的:

{1: Female, Postgrad, American, Yes, No, No, Yes, Yes, No...} and so on. I am still a newbie and so far this is what I tried:

with open('surveys.csv', 'r') as f:
    reader = csv.reader(f, delimiter=' ')
    with open('new_surveys.csv', mode='w') as outfile:
            writer = csv.writer(outfile)
            mydict = {rows[0]:rows for rows in reader}
            print(mydict)

但这会打印出类似的内容

But this prints something like:

{'\ ufeff':['\ ufeff"'],'参与者/问题," 1.:['参与者/问题","1.",'性别'],',2. ':[',2.','Level','of','study'],}目前对我来说没有任何意义...

{'\ufeff"': ['\ufeff"'], 'Participant/Question","1.': ['Participant/Question","1.', 'Gender'], ',2.': [',2.', 'Level', 'of', 'study'],} which does not make any sense to me at the moment...

谢谢!

这是一整行数据:

一行完整的数据,还有59条数据,但它们看起来都一样,唯一的不同是/否或一天中的时间

推荐答案

您可以试试吗?

import csv
with open('surveys.csv', 'r') as f:
    reader = csv.reader(f, delimiter=' ') 
    mydict={}
    iterreader = iter(reader)
    next(iterreader)
    for row in iterreader:
        elementsList=row[0].split("\t")
        nonEmptyElements=[]
        for element in elementsList[1:]:
            print(element)          
            if(not element.strip()==""):
                nonEmptyElements.append(element)
        valuesList=",".join(nonEmptyElements)
        mydict[elementsList[0]]=valuesList
print(mydict)  

我的CSV看起来像这样

My CSV looks like this

Participant Name    Gender
1   Rupin   Male
2   Poonam  Female
3   Jeshan  Male

代码避免使用第一行.

The code avoids using the first row.

我的输出看起来像这样

{'1': 'Rupin,Male', '2': 'Poonam,Female', '3': 'Jeshan,Male'}

这篇关于使用csv文件中的行号创建字典[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆