Reputation: 3
I have a csv file of the format:
spelling, pronunciation, syllables, tag
head, H-EH-D, 1, NSING
bottle, B-O-T-UH-L, 2, NSING
fall, F-AW-L, 1, VBASE
I would like to convert it into a dictionary of the form: 'head' : ['H-EH-D', '1', 'NSING']
Upvotes: 0
Views: 255
Reputation: 11
I had created test.csv file with only two inputs as followed:
head,H-EH-D,1,NSING
bottle,B-O-T-UH-L,2,NSING
My code:
import csv
my_dict = {}
with open('test.csv', mode='r') as infile:
reader = csv.reader(infile)
for row in reader:
key, value = row[0], row[1:]
# my_dict={rows[0]:rows[1:] for rows in reader}
my_dict[key] = value
print(my_dict)
The output of the above code looks like:
{'head': ['H-EH-D', '1', 'NSING'], 'bottle': ['B-O-T-UH-L', '2', 'NSING']}
Upvotes: 1
Reputation: 97
(using csv library, thank for the suggestion @Serge Ballesta)
This solution may work for you :
import csv
result = {}
# open file
with open("file.csv", "r") as csv_file:
parsed_csv = csv.reader(csv_file) # parse data with csv library
next(parsed_csv) # skip first line
# store line in dictionnary
for line in parsed_csv:
result[line[0]] = line[1:]
print(result)
This code will print :
{"head": ["H-EH-D", "1", "NSING"], "bottle": ["B-O-T-UH-L", "2", "NSING"], "fall": ["F-AW-L", "1", "VBASE"]}
for your example.
Upvotes: 1