1

I have a dictionary that looks like this:

dictionary = {'Alice': ['10', '10'], 'Tom': ['9', '8'], 'Ben': ['10', '9']}

I have created a csv file using this dictionary by using the following code which I have taken & adapted from a previous post (How do I write a Python dictionary to a csv file?):

with open('test.csv', 'w') as file:  
writer = csv.DictWriter(file, dictionary.keys(), lineterminator="\n")
writer.writeheader()
writer.writerow(dictionary)

This creates a csv file that looks like this:

Alice, Tom, Ben 
['10', '10'], ['9', '8'], ['10', '9']

But I would like to create a csv file that looks like this:

Alice, ['10', '10']
Tom, ['9', '8']
Ben, ['10', '9']
Community
  • 1
  • 1
user3049921
  • 49
  • 1
  • 1
  • 6
  • http://stackoverflow.com/questions/8685809/python-writing-a-dictionary-to-a-csv-file-with-one-line-for-every-key-value – michaelgulak Mar 08 '15 at 15:20

1 Answers1

0

You need to loop over your dictionary items then write them:

dictionary = {'Alice': ['10', '10'], 'Tom': ['9', '8'], 'Ben': ['10', '9']}

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    for item in dictionary.items():
         spamwriter.writerow(item)

Result:

Ben     ['10', '9']
Alice   ['10', '10']
Tom     ['9', '8']
Mazdak
  • 105,000
  • 18
  • 159
  • 188