如何解决“ DictReader”对象不是下标错误?

时间:2020-11-06 18:14:19

标签: python python-3.x csv dictionary

我正在尝试导入一个csv,然后使用f字符串将结果打印为句子。

我的csv看起来像这样:

"MONTH(purchases.date)","total_revenue_per_month"
"1","264510"
"2","226199"
"3","247469"
"4","254352"
"5","281448"
"6","258480"
"7","260668"
"8","263922"
"9","127317"

我要使用的代码是:

import csv

with open('total_revenue.csv') as csvfile:
    MonthlyRevenue = csv.DictReader(csvfile, delimiter=",", quotechar = '"')
    
for row in MonthlyRevenue:
    print (f"For the month {MonthlyRevenue['MONTH(purchases.date)']} the total revenue was {MonthlyRevenue['total_revenue_per_month']}.")

当我运行代码时,我得到TypeError:'DictReader'对象不可下标。这个错误是什么意思?我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要从每个row而不是DictReader实例访问密钥。

例如,使用

row['MONTH(purchases.date)']

而不是

MonthlyRevenue['MONTH(purchases.date)']

在对象MonthlyRevenue上进行迭代会给您每一行作为dict。就是您可以根据需要访问的词典,例如在此csv示例中。