Reading CSV file and storing the data in a vector

0

I have the following difficulty: I need to read the data that is inside a CSV file and store it in an array to perform calculations with such data, but I do not know how to do it. I am using Python 3.6. Thank you in advance.

My code looks like this: import csv

with open("arquivo.CSV") as arquivocsv:
    ler = csv.DictReader(arquivocsv, delimiter=",")
    for linha in ler:
        print(linha)

What I need is to read the csv file containing 6 columns with the required data and store it in 6 different arrays / lists, one for each column, to perform the calculations.

    
asked by anonymous 27.04.2017 / 17:37

1 answer

1
dados = {} 
with open("arquivo.CSV") as arquivocsv:
    ler = csv.DictReader(arquivocsv, delimiter=",")
    for linha in ler:
        for chave, valor in linha.items():
            if chave not in dados:
                 dados[chave] = []
            dados[chave].append(valor)

It's not that hard. This form is good for those who do not know Python and it is well readable. With a more experienced team, you can use the setdefault method of dictionaries: they already give you a new value if there is not one - thus, you save two lines:

dados = {} 
with open("arquivo.CSV") as arquivocsv:
    ler = csv.DictReader(arquivocsv, delimiter=",")
    for linha in ler:
        for chave, valor in linha.items():
            dados.setdefault(chave, []).append(valor))
    
28.04.2017 / 02:12