【问题标题】:Python csv file to data dictionary multiple keysPython csv文件到数据字典多个键
【发布时间】:2019-07-14 10:47:37
【问题描述】:

我有一个包含 4 列的巨大 csv 文件。我正在尝试将它们转换为数据字典。第一列 [0] 应该是主密钥。当我尝试使用字典时,我得到一个关键错误。

csv 文件中的列:代码描述类别详细信息

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

输出: {101:“笔”, 102:'' 103:'书' 104:'纸' }

{ 101:'写作', 102:'东西' 103:'学校', 104:'办公室' }

{ 101:'东西' 102:'东西' 103:'', 104:'' }

【问题讨论】:

  • 你有没有考虑用pandas阅读它,然后把它转换成dictionaryDataFrame to dict
  • 能否添加触发错误的代码行?

标签: python pandas csv data-dictionary


【解决方案1】:

您可以执行以下操作:

import pandas as pd

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

您首先将其作为DataFramePandas 导入,然后使用参数records 将其转换为dictHere 你可以看到to_dict 是如何工作的。

【讨论】:

  • 如果你认为答案是正确的,你可以选择是正确的。谢谢!
猜你喜欢
  • 2014-03-20
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多