Reputation: 1590
Trying to write contents of a dictionary into a .csv file. The dictionary values are tuples. I want each row to contain a key and then iterate over the values and write each in a separate field in the same row:
I wrote this function (where v is a tuple):
def csv_writer(dict, filename):
with open(filename, 'w') as f:
w = csv.writer(f)
for k,v in dict.items():
w.writerow([k, v])
the contents of v appear as a tuple in the csv file, but I want to get something like this:
k1 v1 v2 v3 v4
k2 v1 v5 v6
etc.
Thanks for any tips in advance.
Upvotes: 0
Views: 1717
Reputation: 114035
def csv_writer(dict, filename):
with open(filename, 'w') as f:
outfile = csv.writer(f)
for k,v in dict.items():
outfile.writerow([k] + v)
Upvotes: 1
Reputation: 1645
Use *v
, also called splat
. More info in docs:
https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
Upvotes: 1