Reputation: 109
I would like to to write dictionary to a csv file with one line for every 'key: value' and serial number of keys?
import csv
dict = {"(2,3,4)" : '3', "(201,233,207)" : '23', "(176,247,207)" : '78'}
w = csv.writer(open("data.csv", "w"))
w.writerow(['xval'+ "\t" + 'yval'])
for key, val in dict.items():
w.writerow([str(key)+ "\t" + str(val)])
It creates :
It does not creates tab separated columns. I want tab separated columns and also a extra column with a serial number.
Added:
CSV data sheet looks like this:
Upvotes: 0
Views: 118
Reputation: 81654
Do not add '\t'
yourself. Instead, use the delimiter
argument of csv.writer
.
As a bonus, this code:
with
str
with map
newline=''
becuase csv.writer
tends to add line breaksimport csv
d = {"(2,3,4)": '3', "(201,233,207)": '23', "(176,247,207)": '78'}
with open("data.csv", "w", newline='') as f:
w = csv.writer(f, delimiter='\t')
w.writerow(map(str, (0, 'xval', 'yval')))
for counter, (key, val) in enumerate(d.items(), 1):
w.writerow(map(str, (counter, key, val)))
When opening the file in Excel or any other spreadsheet application make sure to choose tabs as the delimiter.
I haven't used Python 2.7 in ages. I hope this does not terribly fail.
Upvotes: 1