代码之家  ›  专栏  ›  技术社区  ›  Andrew

如何将字典键保存到同一行的csv文件中

  •  0
  • Andrew  · 技术社区  · 8 年前

    我有一个包含值列表的字典结构,我需要将字典键与列表值一起保存。我设法保存了列表值,但我不知道如何将字典键保存到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)
    

    例子:

    enter image description here

    所以最后一列“total reviews”必须包含reviews字典键

    2 回复  |  直到 8 年前
        1
  •  2
  •   Maxim Egorushkin    8 年前

    一个解决方案:

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