Primo Raj
Primo Raj

Reputation: 109

How to write dictionary to a csv file with one line for every 'key: value' and serial number of keys?

enter image description hereI 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:
enter image description here

Upvotes: 0

Views: 118

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

Do not add '\t' yourself. Instead, use the delimiterargument of csv.writer.

As a bonus, this code:

  • Uses with
  • Cleans all the conversions to str with map
  • Opens the file with newline='' becuase csv.writer tends to add line breaks
import 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

Related Questions