CSV file reading and data storage in a vector

Asked

Viewed 4,423 times

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 don’t know how to do it. I’m using Python 3.6. Thanks in advance.

My code is 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 that contains 6 columns with the necessary data and store in 6 different arrays/lists, one for each column, to perform the calculations.

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 is very readable. With a more experienced team, you can use the method setdefault of dictionaries: they already return you a new value if there is no one - so 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))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.