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
– Manuel Jose
It’s just in place of printar, insert into a list
– Eduardo Mendes
I have something like this: list1 = [tuple(line.values()) for line in csv.Dictreader(f)]
– Manuel Jose
list1 = [tuple(line.values()) for line in csv.
– Manuel Jose