Python - 将字典(将“list”作为值)转换为csv文件

时间:2016-11-27 07:34:47

标签: python-2.7 csv dictionary export-to-csv

尝试将下面的字典写入具有所需输出的csv文件中,如下所述。

dict_data = {"1":["xyz"],
             "2":["abc","def"],
             "3":["zzz"]
            }

期望的输出:

1,3,2
xyz,zzz,abc
        def

下面的代码没有按预期工作,因为它保持“abc”和& “def”在同一个单元格中,如下所示。

with open('k.csv','wb') as out_file:
writer = csv.writer(out_file,dialect = 'excel')
headers =  [k for k in dict_data]
items = [dict_data[k] for k in dict_data]
writer.writerow(headers)
writer.writerow(items)

输出:

1,3,2
xyz,zzz,abc,def

2 个答案:

答案 0 :(得分:1)

以下是完整的解决方案:

    import csv
    import os

    class CsvfileWriter:

        '''
        Takes dictionary as input and writes items into a CSV file.

        For ex:-

        Input dictionary:

        dict_data = {"1":["xyz"],"2":["abc","def"],"3":["zzz"]}

        Output: (CSV file)

        1,3,2
        xyz,zzz,abc
        ,,def

        '''

        def __init__(self,dictInput,maxLength=0):

            '''
            Creates a instance with following variables.
            dictInput & maxLength

            dictInput -> dictionary having values(list) of same length

            ex:-
                dict_data = {"1":["xyz",""],"2":["abc","def"],"3":["zzz",""]}

            maxLength -> length of the list

            '''
            self.dictInput = dictInput
            self.maxLength = maxLength

        @classmethod
        def list_padding(cls,dictInput):

            '''
            converts input dictionary having list (as values) of varying lenghts into constant length.
            Also returns class variables dictInput & maxLength

            Note:
            dictInput represents the dictionary after padding is applied.
            maxLength represents the length of the list(values in dictionary) having maximum number of items.

            Ex:-

            input dictionary:

            dict_data = {"1":["xyz"],"2":["abc","def"],"3":["zzz"]}

            output dictionary:

            dict_data = {"1":["xyz",""],"2":["abc","def"],"3":["zzz",""]}


            '''
            cls.dictInput = dictInput
            listValues =  dictInput.values()
            listValues.sort(key = lambda i: len(i))
            maxLength =  len(listValues[-1])

            for i in listValues:
                while(len(i) < maxLength):
                    i.append('')

            return cls(dictInput,maxLength)

        def write_to_csv(self):

            with open('sample_file.csv','wb') as out_file:
                writer = csv.writer(out_file,dialect = 'excel')
                headers =  [k for k in self.dictInput]
                items = [self.dictInput[k] for k in self.dictInput]
                writer.writerow(headers)
                c = 0
                while (c < self.maxLength):
                    writer.writerow([i[c] for i in items])
                    c += 1

    dict_data = {"1":["xyz"],"2":["abc","def"],"3":["zzz"]}

    cf = CsvfileWriter.list_padding(dict_data)

    cf.write_to_csv()

答案 1 :(得分:0)

以下适用于Python 2:

import csv

dict_data = {
    "1":["xyz"],
    "2":["abc","def"],
    "3":["zzz"]
}

def transpose(cols):
    return map(lambda *row: list(row), *cols)

with open('k.csv','w') as out_file:
    writer = csv.writer(out_file,dialect = 'excel')
    headers = dict_data.keys()
    items = transpose(dict_data.values())
    writer.writerow(headers)
    writer.writerows(items)

我无法归功于transpose功能,我从here获取了该功能。它将列列表转换为行列表,自动填充None的列太短的列。幸运的是,csv编写器输出None值的空白,这正是所需要的。

(在Python 3中,map表现不同(无填充),因此需要进行一些更改。)

编辑:适用于Python 2和3的替换transpose函数是:

def transpose(cols):
    def mypop(l):
        try:
            return l.pop(0)
        except IndexError:
            return ''
    while any(cols):
        yield [mypop(l) for l in cols]