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

5
  • Does stackoverflow.com/questions/6740918/… help? Commented Aug 9, 2021 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'] Commented Aug 9, 2021 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. Commented Aug 9, 2021 at 13:18
  • Please edit your question to show the code you've tried and we can help you further Commented Aug 9, 2021 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. Commented Aug 9, 2021 at 13:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sigh..., why do you split the line by hand instead of using the csv module from the standard library?
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']}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.