Python - 将字典(将“list”作为值)转换为csv文件
问题描述:
尝试将下面的字典写入具有所需输出的csv文件,如下所述。Python - 将字典(将“list”作为值)转换为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
答
下面是完整的解决方案:
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()
答
下面的作品在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
函数,我选了你p从here。它将列的列表变成行列表,自动填充None
的列太短。幸运的是,csv写入器为None
值输出空白,这正是需要的。
(在Python 3,map
表现不同(没有填充),所以它需要一些变化。)
编辑:置换transpose
功能,无论对于Python 2里的工作和3:
def transpose(cols):
def mypop(l):
try:
return l.pop(0)
except IndexError:
return ''
while any(cols):
yield [mypop(l) for l in cols]
+0
感谢您的见解@K。 A. Buhr。这是非常诱人的方法,但我有点担心地图功能的版本不兼容。我宁愿写我自己的函数来追加“无”。 – MSH
在你的“期望输出”中,第三行应该是“,, def”,把“def”放在第三列(即标有“2”的那一列)? –
@ K.A.Buhr:是的。 “def”应该放在“abc”正下方的第三列中。 – MSH