Question

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. 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. 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):

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

Was it helpful?

Solution

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. 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top