简体   繁体   English

在python中,如何将CSV文件的列写入字典?

[英]In python, how do I write columns of a CSV file to a dictionary?

I am trying to take a given csv file and define the first column as the keys, whereas each key refers to an array of 2 values, where one value is in the second column and the other value is in the third column. 我试图获取给定的csv文件并将第一列定义为键,而每个键引用一个包含2个值的数组,其中一个值在第二列中,另一个值在第三列中。 In the end, it is not an option to switch the columns into rows and vice versa, seeing as how I have literally hundreds of rows in each csv that I have to work with. 最后,不能将列切换成行,反之亦然,看看我在每个csv中有多少行,我必须使用它。 When I looked online, the only help I could find used syntax with rows, is there any way to work with columns? 当我在线查看时,我能找到的唯一帮助是使用行的语法,有没有办法处理列?

Here is the code I was trying: 这是我尝试的代码:

import csv
reader = csv.reader(open('test.csv'))

result = {}
for row in reader:
    key = column0
    if key in result:
        pass
    result[key] = column1 and column2

print result

And the csv I am testing (test.csv): 我正在测试的csv(test.csv):

g1_and_g2, 0.04286547, -1.45
g2_and_g2, 0.12348197, 3.00
g3_and_g4, 0.03125879, 1.89

When I run the program in terminal, I get the error: 当我在终端中运行程序时,我收到错误:

NameError: name 'g1_and_g2' is not defined

I am pretty new to programming, so any help given is appreciated. 我对编程很新,所以对任何帮助都表示赞赏。 Thanks! 谢谢!

EDIT to add more information: The expected output should just be a dictionary that's like: 编辑以添加更多信息:预期输出应该只是一个字典,如:

g1_and_g2: 0.04286547,-1.45
g2_and_g2: 0.12348197, 3.00
g3_and_g4: 0.03125879, 1.89

So essentially, the strings in the first column should be the keys, and the integers in the second two columns should be values associated with the key in that row. 基本上,第一列中的字符串应该是键,而后两列中的整数应该是与该行中的键相关联的值。

In addition, I am running python 2.7 另外,我正在运行python 2.7

From reading your description I understand your goal to be to open a csv file in which the first item of every line is a column title/key, and the subsequent items are values for cells in the row corresponding to that key. 通过阅读您的描述,我了解您的目标是打开一个csv文件,其中每行的第一项是列标题/键,后续项是与该键对应的行中的单元格的值。 You'd then like to load this all into a dictionary? 那你想把这个全部加载到字典中吗?

This should do something like what you are looking for if that specification is right. 如果该规范是正确的,这应该像您正在寻找的那样。

import csv
with open('test.csv', "r") as f:
    reader = csv.reader(f)
    result = {}

    for row in reader:
        key = row[0]
        result[key] = row[1:]

    print(result)

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

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