我有以下数据
{'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
我希望将其打印到csv文件中,如下所示:
index similar markets
1 [0,2] ['A','C']
2 [1,2] ['B','C']
3 [2,1] ['A','B']
目前我的代码如下:
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, a.keys())
w.writeheader()
w.writerow(a)
并打印:
index similair markets
[1, 2, 3] [[0, 2], [1, 2], [2, 1]] [['A', 'C'], ['B', 'C'], ['A', 'B']]
答案 0 :(得分:3)
import csv
a = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
keys = ['index', 'similar', 'markets']
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.writer(f)
w.writerow(keys)
w.writerows(zip(*[a[key] for key in keys]))
CSV文件:
index,similar,markets
1,"[0, 2]","['A', 'C']"
2,"[1, 2]","['B', 'C']"
3,"[2, 1]","['A', 'B']"
答案 1 :(得分:2)
您可以使用pandas
库:
import pandas as pd
x = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
x = pd.DataFrame(x)
x.to_csv('mycsvfile.csv', index = False)
csv将是:
index,markets,similar
1,"['A', 'C']","[0, 2]"
2,"['B', 'C']","[1, 2]"
3,"['A', 'B']","[2, 1]"