我有一个包含值列表的字典结构,我需要将字典键与列表值一起保存。我设法保存了列表值,但我不知道如何将字典键保存到csv文件中的同一行。
我的代码示例
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)
例子:
所以最后一列“total reviews”必须包含reviews字典键