【问题标题】:Reading CSV file Into a Dictionary (KeyError: '","')将 CSV 文件读入字典 (KeyError: '","')
【发布时间】:2018-08-07 15:23:57
【问题描述】:

我想将 CSV 文件读入字典,这是我的代码:

import csv
import sys

with open('/Users/m/based_final.csv',mode='r') as my_input_file:
    csv_reader=csv.DictReader(my_input_file)
    line_count=0
    for row in csv_reader:
        if line_count == 0:
            print(str.format('Column names are {",".join(row)}'))
            line_count += 1

        print(str.format('\t{row["Indication"]} {row["Name"]} {row["Drug id"]} {row["Synonyms"]} '))
        line_count += 1
    print('Processed {line_count} lines.')

但我收到此错误: 键错误:'","'。

数据如下所示:

Indication      Name            Drug id                                Synonyms 
for_treatment   bivalirudin     ['db00006', 'btd00076']                ['bivalirudina', 'bivalirudinum', 'hirulog'] 
for_alteplase   a name          ['db00009', 'btd00050', 'biod00050']   ['alteplase (genetical recombination)', 'alteplase, recombinant']    

知道如何解决这个问题吗? 谢谢

【问题讨论】:

  • 包含数据截图。在这种特殊情况下,我们不知道实际数据的样子,而这正是解析器所抱怨的。请包括文本数据。还请包含完整错误消息。
  • 已更正! @DYZ 谢谢!
  • 那么,您的列实际上是制表符分隔的,而不是逗号分隔的吗?另外,请附上完整的错误信息。
  • @DYZ 是的。它是制表符分隔的,但仍使用“\t”,我收到此错误“KeyError: '"\t"'。
  • print('Processed {line_count} lines.') 将打印“已处理的 {line_count} 行。”。你可能想要print(f'Processed {line_count} lines.')。 (注意字符串前面的f。)

标签: python-3.x dictionary


【解决方案1】:

这是用 cmets 修复的代码,告诉我更改了什么,但是,您需要更改文件中的第一行才能使用此代码。 CVS 文件的第一行需要格式化。您想要在字典中使用的每个键都需要在其后加上一个逗号。昏迷周围也不能有任何空间。

import csv
import sys

with open('/Users/m/based_final.csv',mode='r') as my_input_file:
    csv_reader=csv.DictReader(my_input_file)
    line_count=0
    for row in csv_reader:
        if line_count == 0:
            print(str.format(f'Column names are {", ".join(row)}')) # an f added before the single quotes and a space after the coma for readibility
            line_count += 1

        print(str.format(f'\t{row["Indication"]} {row["Name"]} {row["Drug id"]} {row["Synonyms"]} ')) # same thing with the f
        line_count += 1
    print(f'Processed {line_count} lines.') # ditto

【讨论】:

  • 谢谢。但现在我收到此错误:TypeError: sequence item 4: expected str instance, NoneType found。错误在这一行: print(str.format(f'Column names are {", ".join(row)}'))。 @Gabriel Tucker
  • 没问题@nina_dev
猜你喜欢
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2018-03-19
相关资源
最近更新 更多