简体   繁体   English

如何将字典密钥保存到同一行的CSV文件中

[英]How to save dictionary key into csv file on the same row

I have a dictionary structure which contains the list of values, I need to save dictionary key alongside with lists value. 我有一个包含值列表的字典结构,我需要将字典键和列表值一起保存。 I managed to save list values but I don't know how to save dictionary key to the same row in CSV file. 我设法保存列表值,但是我不知道如何将字典键保存到CSV文件的同一行。

example of my code 我的代码示例

import csv

product_dict = {}
review = 10
product_link = "www.ebay.com"
product_title = "T-shirt"
product_price = 15.99
asin_code = "A9439"
product_dict[review] = [product_link, product_title, product_price, asin_code]

#Sort dictionary in descending order    
sorted_dict = collections.OrderedDict(sorted(product_dict.items(), reverse=True)) 
getNProducts = {k: sorted_dict[k] for k in sorted_dict.keys()[1:total_products+1]}

#Save Data to CSV File
with open("testfile", 'a') as out_file:
      writer = csv.writer("testfile.csv", dialect = 'excel')
      keys = getNProducts.keys()
      items = getNProducts.values()
      writer.writerows(items)

example: 例:

在此处输入图片说明

So the last column "Total REviews" has to contain reviews dictionary key 因此,最后一栏“ Total REviews”必须包含评论字典关键字

One solutions: 一种解决方案:

writer = csv.writer("testfile.csv", dialect = 'excel')
for k, v in getNProducts.iteritems():
    writer.writerow(list((k,)) + list(v))    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM