【问题标题】:writing list of tuples within a dictionary to csv将字典中的元组列表写入 csv
【发布时间】:2016-04-09 19:05:27
【问题描述】:

我有一个字典,'allData' 包含元组列表。

allData = {'Shirts': [(69.95, 1), (52.45, 2), (99.95, 3), (79.95, 4), (79.95, 5)],
           'Jeans': [(70.0, 1), (50.0, 2), (99.0, 3), (79.95, 4), (80.0, 5)]}

我想将每个键及其元素写入 csv 文件。

我目前的代码如下:

def writeCSV(path, filename,  d):
    filename = path + filename

    with open(filename, 'wb') as outfile:
        writer = csv.writer(outfile, delimiter='~')
        writer.writerow(d.keys())
        writer.writerows(izip_longest(*d.values()))

    print "write file complete"

writeCSV("C:\\Projects\\Output", "output.csv", allData)

这在 excel 中为我提供了以下输出,其中 Shirts 和 Jeans 是 A 列和 B 列。

Shirts      Jeans
(69.95, 1)  (49.95, 1)
(52.45, 2)  (0.0, 2)
(99.95, 3)  (104.95, 3)
(79.95, 4)  (59.95, 4)
(79.95, 5)  (80.0, 5)

这是我实际需要的输出,其中 Shirts, id, Jeans, id 分别是 A、B、C、D 列。

Shirts  id  Jeans   id
69.95   1   70.0    1
52.45   2   50.0    2
99.95   3   99.0    3
79.95   4   79.95   4
79.95   5   80.0    5

非常感谢任何帮助。

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    另一种可能的解决方案:

    import os
    import csv
    
    from itertools import izip_longest
    
    def writeCSV(path, filename, d):
        def flatten(l):
            return [t[i] for t in l for i in range(len(t))]
    
        filename = os.path.join(path, filename)
    
        with open(filename, 'wb') as outfile:
            writer = csv.writer(outfile, delimiter='~')
            keys = d.keys()
            writer.writerow(flatten(zip(keys, ['id'] * len(keys))))
            # Keep the values in the same order as keys
            values = [d[key] for key in keys]
            writer.writerows(flatten(row) for row in izip_longest(*values, fillvalue=('', '')))
            print "write file complete"
    
    writeCSV("C:\\Projects\\Output", "output.csv", allData)
    

    【讨论】:

      【解决方案2】:

      这行得通:

      import csv
      import os
      
      def writeCSV(path, filename,  d):
          filename = os.path.join(path, filename)
          col_names = list(d.keys())
          header = []
          for name in col_names:
              header.append(name)
              header.append('id')
      
          with open(filename, 'wb') as outfile:
              writer = csv.writer(outfile) # change delimiter with `delimiter=' '`
              writer.writerow(header)
              index = 0
              end = max([len(x) for x in d.values()])
              while index < end:
                  line = []
                  for name in col_names:
                      try:
                          row_values = d[name][index]
                      except IndexError:
                          row_values = [''] * len(col_names)
                      line.extend(row_values)
                  writer.writerow(line)
                  index += 1
      

      使用大小不等的数据:

      allData = {'Shirts': [(69.95, 1), (52.45, 2), (99.95, 3), (79.95, 4), (79.95, 5)],
                 'Jeans': [(70.0, 1), (50.0, 2), (99.0, 3), (79.95, 4), (80.0, 5) , (80.0, 5)]}
      
      writeCSV(os.getcwd(), "csv_output.csv", allData)
      

      csv_output.csv的内容:

      Jeans,id,Shirts,id
      70.0,1,69.95,1
      50.0,2,52.45,2
      99.0,3,99.95,3
      79.95,4,79.95,4
      80.0,5,79.95,5
      80.0,5,,
      

      请注意,Jeans 的列更长,因为它在输入字典中多了一个数据集。

      【讨论】:

        猜你喜欢
        • 2014-06-17
        • 2016-03-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多