[英]Append Dictionary or list of values at the end of each row in csv using python
[英]Store dictionary with list values in csv using python
这是我的字典结构
dic = {'tt3832096': ['remake', 'horror-movie-remake', 'flesh-eating-virus', 'gore'],
'tt6217804': ['chainsaw', 'sequel', 'second-part', 'mable-simmons-character']}
我想将其保存在csv文件中,如下所示:
movie id keyword
tt3832096 ['remake', 'horror-movie-remake', 'flesh-eating-virus', 'gore']
tt6217804 ['chainsaw', 'sequel', 'second-part', 'mable-simmons-character']
我已经试过了:
with open('test.csv', 'w') as f:
for key in dic.keys():
f.write("%s:%s\n"%(key,dic[key]))
但这将每个价值项放在一个单元格中。 有没有更好的办法?
您可以将带有标签的csv.writer
用作分隔符:
import csv
d = {'tt3832096': ['remake', 'horror-movie-remake', 'flesh-eating-virus', 'gore'], 'tt6217804': ['chainsaw', 'sequel', 'second-part', 'mable-simmons-character']}
with open('output.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(['movie id', 'keyword'])
for k, v in d.items():
writer.writerow([k, v])
如果您可以使用3rd party库,那么对Pandas来说这是微不足道的:
import pandas as pd
# construct dataframe from dictionary d
df = pd.DataFrame(list(d.items()), columns=['movie id', 'keyword'])
# export to csv
df.to_csv('file.csv', index=False)
但是,实际上,如果计划将文件读回Python, 则不建议这样做。 在这种情况下,您可以使用Pickle(取决于版本)来存储和拾取具有列表值的字典:
import pickle
with open('d_file.pkl', 'wb') as fout:
pickle.dump(d, fout, protocol=pickle.HIGHEST_PROTOCOL)
with open('d_file.pkl', 'rb') as fin:
d = pickle.load(fin)
您显示的行如下所示:
tt3832096 ['remake', 'horror-movie-remake', 'flesh-eating-virus', 'gore']
不是CSV文件的一部分,或者至少不是您要考虑的结构的CSV文件。 作为CSV记录,此行包含四个看起来像这样的值(或类似的值,具体取决于解码时对引号字符的处理方式)。
tt3832096 ['remake'
'horror-movie-remake'
'flesh-eating-virus'
'gore']
如果您确实要将其另存为CSV文件,则最好的选择是这样的:
'tt3832096', 'remake', 'horror-movie-remake', 'flesh-eating-virus', 'gore'
应该与您现在生产的相似。
如果您想以更像它来自的字典的格式存储它,则有几种选择:
pickle
可以保留结构,但生成的文件不可读。 json
库使用JSON序列化,该库会生成可保存词典结构的人类可读的标准json文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.