Python:将字典打印到csv,每个键值都在一个新行中

时间:2016-11-10 22:45:36

标签: python python-2.7 pandas

我有以下数据

{'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']]

2 个答案:

答案 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]"