I'm looking for a way to write a python dictionary to columns (keys in first column and values in second). This link shows how to write a list to a column, but am wondering if there is a way to do this without converting my dictionary to two zipped lists.
myDict = {1:'a', 2:'b', 3:'c'}
keyList = myDict.keys()
valueList = myDict.values()
rows = zip(keyList, valueList)
with open('test.csv', 'wb') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
desired result:
1;a
2;b
3;c
You could simply do in python 2.X :
with open('test.csv', 'wb') as f:
writer = csv.writer(f)
for row in myDict.iteritems():
writer.writerow(row)
For python 3.X, change the for loop line to for row in myDict.items():
A slightly shorter version is to do:
rows = myDict.iteritems()
(Or .items()
for Python 3.)
To get the ;
separator, pass delimiter
to csv.reader
or csv.writer
. In this case:
writer = csv.writer(f, delimiter=';')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With