[英]Python csv file to data dictionary multiple keys
I have a huge csv file with 4 columns. 我有一个巨大的csv文件,其中包含4列。 i'm trying to convert them into a data dictionary.
我正在尝试将它们转换为数据字典。 the first column [0] should be the master key.
第一列[0]应该是主密钥。 when i try to use the dictionary i get a key error.
当我尝试使用字典时,出现键盘错误。
columns in csv file:Code Description Category Detail csv文件中的列:代码说明类别详细信息
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:'pen',102:''103:'book'104:'paper'}
{ 101:'Writing', 102:'stuff', 103:'school', 104:'office' } {101:“写作”,102:“东西”,103:“学校”,104:“办公室”}
{ 101:'stuff', 102:'stuff', 103:'', 104:'' } {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
. 您首先要从
Pandas
将其作为DataFrame
导入,然后将其转换为带有参数records
的dict
。 Here you can see how to to_dict
works. 在这里,您可以了解
to_dict
工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.