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

Asked

Viewed 1,043 times

2

The data in the.csv cities 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 list item?

1 answer

2


If you need to convert a csv to a dictionary, your code is correct then I will use it as a basis for response. 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 the values

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

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

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

Using your code as the basis, 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')
  • yes but I want to store all these Tuples in a list and then use the attribute "distance" to calculate the shortest path between two cities

  • It’s just in place of printar, insert into a list

  • I have something like this: list1 = [tuple(line.values()) for line in csv.Dictreader(f)]

  • list1 = [tuple(line.values()) for line in csv.

Browser other questions tagged

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