Reputation: 43
I have a dictionary that looks like this:
scores = {'Tom': [9, 8], 'Alice': [10, 10], 'Ben': [10, 9]}
I am outputting these scores to the csv file in the following way:
file = open("test.csv","w")
writer = csv.writer(file, delimiter=',', lineterminator="\n")
for item in scores.items():
writer.writerow(item)
This creates a csv file that looks like this:
Tom, [9, 8]
Alice, [10, 10]
Ben, [10, 9]
How can I remove the brackets and comma so I am left with just the numbers? - [ , ]
I would like to create a csv file that looks like this:
Tom, 9 8
Alice, 10 10
Ben, 10 9
Upvotes: 1
Views: 158
Reputation: 180482
Your delimiter is set to delimiter=','
so that is what you are going to get. If you want different delimiters you may as well just use the a normal file.write but having different delimiters is not going to help when you decide to read the contents again.
for k,v in scores.items():
writer.writerow([k]+ v)
Output:
Tom,9,8
Ben,10,9
Alice,10,10
If you really want to mix both you can add a comma to the key but if I were you I would pick one delimiter:
with open("test.csv","w") as f:
writer = csv.writer(f, delimiter=' ', lineterminator="\n")
for k,v in scores.items():
writer.writerow([k+","]+ v)
Upvotes: 1