BOBjwjwj3j3j
BOBjwjwj3j3j

Reputation: 141

Writing a dictionary value that is a list without brackets to CSV

I have a dictionary, d with the following structure:

{'k':[5, -2, 6, 7, 2, 4, 8], 'c':[6, 3, 1, 2, 3, 4, 9]}

I want to write this to a .csv file that looks like:

k, 5, -2, 6, 7, 2, 4, 8
c, 6, 3, 1, 2, -3, 4, 9

I tried the following code:

with open('file.csv', 'w') as f:
    for key in d.keys():
        f.write("%s,%s\n"%(key,d[key]))

This, unfortunately produces the following:

k, [5, -2, 6, 7, 2, 4, 8]
c, [6, 3, 1, 2, -3, 4, 9]

The solution I have is to just run a tr or sed command after, but there must to be a way to just write it properly the first time, right?

Upvotes: 1

Views: 650

Answers (3)

Mykola Zotko
Mykola Zotko

Reputation: 17834

You can use the function join:

with open('file.csv', 'w') as f:
    for k, lst in dct.items():
        lst = ','.join(map(str, lst))
        f.write('%s,%s\n' % (k, lst))

Upvotes: 0

Samwise
Samwise

Reputation: 71477

I'd suggest first building the lists that you want to write out as a CSV:

>>> [[k] + v for k, v in d.items()]
[['k', 5, -2, 6, 7, 2, 4, 8], ['c', 6, 3, 1, 2, 3, 4, 9]]

From there your original code will work, but I'd also suggest using csv.writer rather than rolling your own formatting:

import csv
with open('file.csv', 'w') as file:
    csv_writer = csv.writer(file)
    for row in [[k] + v for k, v in d.items()]:
        csv_writer.writerow(row)

Upvotes: 3

Andrej Kesely
Andrej Kesely

Reputation: 195478

d = {'k':[5, -2, 6, 7, 2, 4, 8], 'c':[6, 3, 1, 2, 3, 4, 9]}

with open('file.csv', 'w') as f:
    for key in d.keys():
        print(key, *d[key], sep=', ', file=f)

Prints to file:

k, 5, -2, 6, 7, 2, 4, 8
c, 6, 3, 1, 2, 3, 4, 9

Upvotes: 4

Related Questions