Marc Zaharescu Marc Zaharescu - 22 days ago 7
Python Question

Python: print dictionary to csv, each key value in a new line

I have the following data

{'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}


and I want to print it to a csv file as following:

index similar markets
1 [0,2] ['A','C']
2 [1,2] ['B','C']
3 [2,1] ['A','B']


currently my code is as following:

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)


and it prints:

index similair markets
[1, 2, 3] [[0, 2], [1, 2], [2, 1]] [['A', 'C'], ['B', 'C'], ['A', 'B']]

Answer
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 file:

index,similar,markets
1,"[0, 2]","['A', 'C']"
2,"[1, 2]","['B', 'C']"
3,"[2, 1]","['A', 'B']"
Comments