Daringa Daringa - 1 month ago 10
Python Question

Print Dictionary with commas separating values

import csv
import output
fill = input("Enter File name:")
f = open(fill)
csv_f = csv.reader(f)
m = open('data.csv', "w")
dict_out = {}
for row in csv_f:
if row[1] in dict_out:
dict_out[row[1]] += row[3]
else:
dict_out[row[1]] = row[3]
for title, value in dict_out.items():
m.write('{},'.format(title))
m.write ('{} \n'.format(value))

m.close()


Prints my csv as

Title,Detail
Siding, 50 63 22 68 138 47 123 107 107 93 117
Asphalt, 49 8 72 19 125 95 33 83 123 144
Rail, 82 98 89 62 58 66 24 77 120 93
Grinding, 127 47 20 66 29 137 33 145 3 98
Concrete, 130 75 12 88 22 137 114 88 143 16


I would like to put a comma in between the numbers. I have tried
m.write(',')
after
m.write('{} \n'.format(value))
but it only adds it after the last one. How can i format it so it will output as

Title,Detail
Siding, 50,63,22,68,138,47,123,107,107,93,117
Asphalt, 49,8,72,191,25,95,33,83,123,144
Rail, 82,98,89,62,58,66,24,77,120,93
Grinding, 127,47,20,66,29,137,33,145,3,98
Concrete, 130,75,12,88,22,137,114,88,143,16

Answer

not the best way but you can:

for title, value in dict_out.items():
    m.write('{},'.format(title))
    m.write ('{} \n'.format(value.replace(' ', ',')))

but you should definetly use csv writter,

import csv  
import output

fill = input("Enter File name:")
f = open(fill)
csv_f = csv.reader(f)
c = open('data.csv', "w")
m = csv.writer(c)
dict_out = {}

for row in csv_f:
 if row[1] in dict_out:
     dict_out[row[1]].append(row[3])
 else:
     dict_out[row[1]] = [row[3]]

for title, value in dict_out.items():
    m.writerow([title] + value)

c.close()