Read Data from a .csv file and pass line values to Tuple

2

The data in the cities.csv file is organized as follows:

Lisbon, Madrid, 600

Madrid, Paris, 650

import csv
with open('cidades.csv', 'r') as f: # Somente r para leitura do arquivo
      list1 = [tuple(line.values()) for line in csv.DictReader(f)]

How do I read the values for each tuple in the list?

    
asked by anonymous 09.11.2017 / 02:53

1 answer

2

If you need to convert a csv to a dictionary, your code is correct so I'll use it as the basis for the answer. When you use csv.DictReader it creates a dictionary based on the keys and values of each column. For example:

First line of csv:

| Nome | Telefone | Cidade |

And the consequent lines with values

| Manoel  | 999999999 | Lisboa    |
| Eduardo | 888888888 | São Paulo |

When the DictReader function is applied to this csv, it will return an iterable one and each list element will be a dictionary with the value keys:

{'Cidade': 'Lisboa', ' Nome': ' Manoel', 'Telefone': '999999999'}
{'Cidade': 'São Paulo', ' Nome': ' Eduardo', 'Telefone': '888888888'}

Based on your code, we have something very similar to what you want, come on:

import csv
with open('arquivo.csv', 'r') as f: # Somente r para leitura do arquivo
    ler = csv.DictReader(f)
    for linha in ler:
        # Cada linha aqui, já um dicionário completo, porém, se precisar
        # transformar o mesmo em uma tupla pode usar dict.values()
        print(tuple(linha.values()))

What will return something like this:

('Lisboa', ' Manoel', '999999999')
('São Paulo', ' Eduardo', '888888888')
    
09.11.2017 / 11:57