0

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']

Hermit
  • 3
  • 3
  • Does https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file help? – alfinkel24 Aug 09 '21 at 13:03
  • You can't have a dictionary entry that looks like that. I suggest either:- 'head': 'H-EH-D, 1, NSING' or 'head': ['H-EH-D', '1', 'NSING'] –  Aug 09 '21 at 13:08
  • @DarkKnight edited as per your suggestion and to alfinkel24 thank you but it doesn't seem to have exactly what I'm looking for. – Hermit Aug 09 '21 at 13:18
  • Please edit your question to show the code you've tried and we can help you further –  Aug 09 '21 at 13:22
  • I've tried a few things such as using the csv.DictReader module and creating a none-type object in dictionary format but they're all separate implementations. I wanted a fresh implementation, if that makes sense as none of them quite does what I want. – Hermit Aug 09 '21 at 13:46

2 Answers2

1

(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.

1

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']}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Bishikh
  • 11
  • 2