Reputation: 103
I have a dictionary of the following form
>>> {'1' : [V3210 , 234567 ,1235675 , 23], '2' : [v3214 , 5678 ,65879 ,89} , ...}
How to write dictionary into csv form, like so:
1 V3210 234567 12345675 23
2 v3214 5678 65879 89
I tried:
for key, value in van.iteritems():
w.writerow([key, value])
Upvotes: 1
Views: 41
Reputation: 14141
import csv
van = {'1' : ['V3210' , 234567 ,1235675 , 23], '2' : ['v3214' , 5678 ,65879 ,89]}
with open('some_name.csv', 'w', newline='') as csvfile:
my_writer = csv.writer(csvfile, delimiter='\t',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
for key, val in van.items():
my_writer.writerow([key] + val)
some_name.csv
:
1 V3210 234567 1235675 23 2 v3214 5678 65879 89
Upvotes: 1
Reputation: 13175
Your attempt was super-close. You need to "unpack" the values stored in the list using *
(the "splat" operator):
for key, value in van.iteritems():
w.writerow([key, *value])
I think this should work in 2.7. Note that Python 2.x comes to the end of its life within a year so it's time to think of moving to Python 3.
If it doesn't work, you can concatenate the lists:
w.writerow([key] + value)
The bottom line is that writerow
expects a 1D list to represent that row. In the concatenation case, we have to enclose key
in a list first. Otherwise we can just unpack the value
list items into the main list.
Upvotes: 0