将列表字典写入CSV文件
我在把一个包含列表的字典写入.csv文件时遇到了困难。
我的字典长这样:
dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]
我希望生成的.csv文件看起来像这样:
key1 key2 key3
1 4 7
2 5 8
3 6 9
首先,我写入表头:
outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())
到目前为止一切都很好……不过,我的问题是我不知道怎么把一个列表对应到正确的列上。例如:
for i in range(0,len(dict[key1])):
writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])
这样会随机填充列。另一个问题是,我必须手动填写键,不能用它来处理另一个有4个键的字典。
6 个回答
2
保存:
with open(path, 'a') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict_.items():
writer.writerow([key, ','.join(value)])
csv_file.close()
print ('saving is complete')
读取:
with open(csv_path, 'rb') as csv_file:
reader = csv.reader(csv_file);
temp_dict = dict(reader);
mydict={k:v.split(',') for k,v in temp_dict.items()}
csv_file.close()
return mydict
2
给定
dict = {}
dict['key1']=[1,2,3]
dict['key2']=[4,5,6]
dict['key3']=[7,8,9]
以下代码:
COL_WIDTH = 6
FMT = "%%-%ds" % COL_WIDTH
keys = sorted(dict.keys())
with open('out.csv', 'w') as csv:
# Write keys
csv.write(''.join([FMT % k for k in keys]) + '\n')
# Assume all values of dict are equal
for i in range(len(dict[keys[0]])):
csv.write(''.join([FMT % dict[k][i] for k in keys]) + '\n')
生成的csv文件看起来像:
key1 key2 key3
1 4 7
2 5 8
3 6 9
2
自己动手,不用csv模块:
d = {'key1' : [1,2,3],
'key2' : [4,5,6],
'key3' : [7,8,9]}
column_sequence = sorted(d.keys())
width = 6
fmt = '{{:<{}}}'.format(width)
fmt = fmt*len(column_sequence) + '\n'
output_rows = zip(*[d[key] for key in column_sequence])
with open('out.txt', 'wb') as f:
f.write(fmt.format(*column_sequence))
for row in output_rows:
f.write(fmt.format(*row))
4
这个方法即使在关键字里的列表长度不一样时也能正常工作。
with myFile:
writer = csv.DictWriter(myFile, fieldnames=list(clusterWordMap.keys()))
writer.writeheader()
while True:
data={}
for key in clusterWordMap:
try:
data[key] = clusterWordMap[key][ind]
except:
pass
if not data:
break
writer.writerow(data)
你可以使用pandas把它保存成csv格式:
df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)
48
如果你不在乎列的顺序(因为字典是没有顺序的),你可以直接使用 zip()
:
d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(zip(*d.values()))
结果:
key3 key2 key1
7 4 1
8 5 2
9 6 3
如果你在乎顺序,那你就需要先对键进行排序:
keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile, delimiter = "\t")
writer.writerow(keys)
writer.writerows(zip(*[d[key] for key in keys]))
结果:
key1 key2 key3
1 4 7
2 5 8
3 6 9