Python: print dictionary to csv, each key value in a new line -
i have following data
{'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['a', 'c'], ['b', 'c'], ['a', 'b']]} and want print csv file following:
index similar markets 1 [0,2] ['a','c'] 2 [1,2] ['b','c'] 3 [2,1] ['a','b'] currently code following:
with open('mycsvfile.csv', 'wb') f: # use 'w' mode in 3.x w = csv.dictwriter(f, a.keys()) w.writeheader() w.writerow(a) and prints:
index similair markets [1, 2, 3] [[0, 2], [1, 2], [2, 1]] [['a', 'c'], ['b', 'c'], ['a', 'b']]
import csv = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['a', 'c'], ['b', 'c'], ['a', 'b']]} keys = ['index', 'similar', 'markets'] open('mycsvfile.csv', 'wb') f: # use 'w' mode in 3.x w = csv.writer(f) w.writerow(keys) w.writerows(zip(*[a[key] key in keys])) csv file:
index,similar,markets 1,"[0, 2]","['a', 'c']" 2,"[1, 2]","['b', 'c']" 3,"[2, 1]","['a', 'b']"
Comments
Post a Comment