簡體   English   中英

將字典中的元組列表寫入CSV

[英]writing list of tuples within a dictionary to csv

我有一本字典,“ 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

任何幫助深表感謝。

這有效:

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

請注意,“牛仔褲”的列較長,因為它在輸入字典中還有一個數據集。

另一個可能的解決方案:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM