Python 如何解决';听写器&x27;对象不可下标错误?

Python 如何解决';听写器&x27;对象不可下标错误?,python,python-3.x,csv,dictionary,Python,Python 3.x,Csv,Dictionary,我正在尝试导入csv,然后使用f字符串将结果打印为句子 我的csv看起来像这样: “月(购买日期)”,“每月总收入” "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: Mon

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

我的csv看起来像这样:

“月(购买日期)”,“每月总收入”
"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”对象是不可订阅的。这个错误意味着什么?如何解决此问题?

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

例如,使用

row['MONTH(purchases.date)']
而不是

MonthlyRevenue['MONTH(purchases.date)']
迭代对象
MonthlyRevenue
会将每一行作为
dict
提供给您。您可以根据需要访问该词典,如本例中所示