简体   繁体   中英

Python csv file to data dictionary multiple keys

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:'' }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM