簡體   English   中英

將字典列表寫到csv中,並在單獨的列中添加值

[英]Write list of dicts to csv with values in separate columns

我很難理解如何將字典列表寫入csv,其中所有值都在單獨的列中。 在SO上與此類似的問題並沒有幫助我理解。 我一直在使用DictWriter,但無法弄清楚如何在沒有錯誤“字段x不在字段名稱中”的情況下輸入dict.values()。

.....

dicts = [
  {'sku': 'xxxx1', 'model': '1234-56K', 'price': '$xxx.xx', 'name': 'item_name_here', 'stock': 'True'},
  {'sku': 'xxxx2', 'model': '1234-56K', 'price': '$xxx.xx', 'name': 'item_name_here', 'stock': 'False'}
]

csv_file = open('file.csv','wb')
fieldnames = ('name', 'price', 'stock', 'model', 'sku')
csvwriter = csv.DictWriter(csv_file, fieldnames, extrasaction='raise', dialect='excel')
csvwriter.writeheader()
csvwriter.writerows(dicts)
return csv_file

.....

這會在單列中返回我的值,但是當我遍歷列表中dict的值時,它只是將所有值(作為字符串)拆分為's,t,r,i,n,g',仍然將它們放入第一列。

csv.DictWriter()的文檔中:

如果傳遞給writerow()方法的詞典包含在字段名中找不到的鍵,則可選的extrasaction參數指示要執行的操作。 如果將其設置為“ raise”,則會引發ValueError。 如果將其設置為“忽略”,則字典中的其他值將被忽略。

如果這是您遇到的錯誤,請嘗試:
csv.DictWriter(csv_file, fieldnames, extrasaction='ignore', dialect='excel')

嘿,我是為Python 2.7編寫的

此函數獲取字典列表並輸出一個csv。 它還包括用於在fieldNames,defaultFieldValues,sortField中設置字段順序的選項,以及用於刪除重復項的選項

https://gist.github.com/brendancol/6816393

def write_csv(outputRowDictionaries, outputFile, fieldNames=None, defaultFieldValue='', removeDuplicates=False, sortField=None):
....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM