Reputation: 3
I have a CSV file like this one:
ALBERO; SHAFT
ALBERINO; SHAFT
MAGGIORATO; EXTRA WIDE
I need to open that file and convert to a dictionary with the following structure:
glossario={"ALBERO" : "SHAFT",
"ALBERINO" : "SHAFT",
"MAGGIORATO" : "EXTRA WIDE" }
I tried to setup the following code, but the output it's not what I expected:
glossario= []
with open(glossarioFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf, delimiter=';')
for line in csvReader:
glossario.append(line)
Anyone has some suggestion?
Thank you.
Upvotes: 0
Views: 401
Reputation: 8596
Here I've used python Dict Comprehensions to write more pythonic code.
import csv
glossario = {}
glossario_file_path = 'your_file_name.csv'
with open(glossario_file_path, encoding='utf-8') as csvf:
csv_reader = csv.reader(csvf, delimiter=';')
glossario = {key: value for key, value in csv_reader}
print(glossario)
{'ALBERO': ' SHAFT', 'ALBERINO': ' SHAFT', 'MAGGIORATO': ' EXTRA WIDE'}
Upvotes: 1
Reputation: 316
DictReader
doesn't do what you want, the keys in the output are the headers (A.K.A the first line of the csv), and the values are the values in the same column as the header https://docs.python.org/3/library/csv.html#csv.DictReader
You want to use a regular csv.reader
and set the values of each line to a dictionary.
import csv
glossario = {}
glossario_file_path = 'glossario.csv'
with open(glossario_file_path, encoding='utf-8') as csvf:
reader = csv.reader(csvf, delimiter=';')
for line in reader:
key = line[0]
value = line[1]
glossario[key] = value
This is how the glossario
variable looks like
{'ALBERO': ' SHAFT', 'ALBERINO': ' SHAFT', 'MAGGIORATO': ' EXTRA WIDE'}
Notice that the values of the dict contain whitespaces, so you might want to add
value = line[1].strip()
to remove them.
Upvotes: 2
Reputation: 306
Use this code for it to work :
glossario= {}
with open(glossarioFilePath, encoding='utf-8') as csvf:
csvReader = csv.reader(csvf, delimiter=';')
for line in csvReader:
glossario[line[0]] = line[1]
I update the dictionnary with the new key/value pair every iteration.
Upvotes: 0