0

I have a huge csv file with 4 columns. i'm trying to convert them into a data dictionary. the first column [0] should be the master key. when i try to use the dictionary i get a key error.

columns in csv file:Code Description Category Detail

csv file

with open('sample.csv') as f:
reader = csv.reader(f)
next(reader,None)
code= {}
description= {}
category = {}
detail = {} 
for row in reader:
    code = {row[0]:row[1]}
    description =  {row[0]:row[2]}
    category = {row[0]:row[3]}
    detail = {row[0]:row[4]}

output: {101:'pen', 102:'' 103:'book' 104:'paper' }

{ 101:'Writing', 102:'stuff', 103:'school', 104:'office' }

{ 101:'stuff', 102:'stuff', 103:'', 104:'' }

2
  • 1
    Have you consider reading it with pandas and then transforming it into a dictionary DataFrame to dict? Commented Feb 20, 2019 at 16:54
  • can you add the line of code that triggers the error? Commented Feb 20, 2019 at 16:54

1 Answer 1

1

You could do the following:

import pandas as pd

df = pd.read_csv("sample.csv")
df.to_dict('records')

You would first import it as a DataFrame from Pandas and then transfrom it into a dict with the argument records. Here you can see how to to_dict works.

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

1 Comment

if you think the answer is correct, you can select is the right one. Thanks!

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.