用逗号分隔值打印字典

时间:2016-10-27 15:46:32

标签: python python-3.x csv

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()

将我的csv打印为

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 

我想在数字之间加一个逗号。我在m.write(',')之后尝试了m.write('{} \n'.format(value)),但它只在最后一个之后添加了它。我如何格式化它以便输出为

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

2 个答案:

答案 0 :(得分:0)

不是最好的方法,但你可以:

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

但你应该绝对使用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()

答案 1 :(得分:0)

如果value是一个字符串,那么你需要使用value.split()。如果它已经是一个列表,那么您不需要使用拆分方法。

with open('data.csv', "w") as m:
    for title, value in dict_out.items():
         m.write(title + "," +  ",".join(value.split()) + "\n")