0

I am quite new to Python so please excuse me if this is a really basic question. I have a Python dictionary such as this one:

foo = {'bar1':['a','b','c'], 'bar2':['d','e']}

I would like to write it to a csv file, with one line per value and the key as first element of each row. The output would be (whatever the quotation marks):

bar1,'a'
bar1,'b'
bar1,'c'
bar2,'d'
bar2,'e'

I have tried this such as suggested here

import csv
with open('blah.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in foo.items():
       writer.writerow([key, value])

but this gives the following output, with one line per key:

bar1,"['a', 'b', 'c']"
bar2,"['d', 'e']"

Thanks for your help!

Community
  • 1
  • 1
tlorin
  • 1,100
  • 6
  • 17
  • 30

1 Answers1

5

This is because [key, value] contains multiple "values" within value. Try iterating over the dictionary like this:

for key, values in foo.items():
    for value in values:
        writer.writerow([key, value])
Ezra Citron
  • 101
  • 2
  • 6
Frangipanes
  • 380
  • 2
  • 14