【问题标题】:How can I get the values from a python dictionary to a CSV file?如何从 python 字典中获取值到 CSV 文件?
【发布时间】:2020-01-22 14:27:42
【问题描述】:

我一直试图在 CSV 文件中获取一份作为字典的报告。但只是值,不包括键。这是我的字典。

这是一个例子。

字典:

{'Type': 'XXXXXX', 'InvoiceID': '123456', 'InvoiceNumber': '001', 'Reference': '', 'Payments': [{'PaymentID': '12345678910', 'BatchPaymentID': '12345678910', 'Date': datetime.datetime(2019, 5, 31, 0, 0), 'Amount': 1000, 'Reference': '', 'CurrencyRate': 1.0, 'HasAccount': False, 'HasValidationErrors': False}]

这是我正在使用的代码。

def get(report,month):
    my_dict = report


    with open('invoices.csv','w') as f:
        w = csv.DictWriter(f, my_dict.keys())
        w.writeheader()
        w.writerow(my_dict)

我得到的错误:

AttributeError: 'list' object has no attribute 'keys'

任何帮助将不胜感激。

【问题讨论】:

  • 正如错误消息所说,您的“dict”实际上是list。问题的原因不在您显示的代码中。

标签: python-3.x csv dictionary


【解决方案1】:

您可以将字典转换为数据框,然后将其写入 csv。

代码:

my_dict={'Type': 'XXXXXX', 'InvoiceID': '123456', 'InvoiceNumber': '001', 'Reference': '', 'Payments': [{'PaymentID': '12345678910', 'BatchPaymentID': '12345678910', 'Date': datetime.datetime(2019, 5, 31, 0, 0), 'Amount': 1000, 'Reference': '', 'CurrencyRate': 1.0, 'HasAccount': False, 'HasValidationErrors': False}]}

df=pd.DataFrame(my_dict)
df.to_csv('invoices.csv',index=None,header=None, mode='w')   #add header=None to exclude the keys. Mode can be changed depending on whether you want to write or append.

输出:

    Type    InvoiceID   InvoiceNumber   Reference   Payments
0   XXXXXX  123456      001                         {'PaymentID': '12345678910', 'BatchPaymentID':...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多