将字典中的元组列表写入csv

时间:2016-04-09 19:05:28

标签: python csv dictionary

我有一个字典,'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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这有效:

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,,

请注意,牛仔裤的列较长,因为它在输入词典中还有一个数据集。

答案 1 :(得分:0)

另一种可能的解决方案:

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)