0

Trying to populate a CSV file using a dictionary.

Here's the code I'm trying:

import csv

my_dict = {'App 1': 'App id1', 'App 2': 'App id2', 'App 3': 'App id3'}
with open('test.csv', 'w') as f:
    fieldnames = ['Application Name', 'Application ID']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(my_dict)

With this code it was only creating a csv file with the header.

I'm looking for a similar output:

enter image description here

Raj
  • 301
  • 2
  • 4
  • 18

2 Answers2

4

You need to reformat your data into a list of dicts such that keys and values from the old dict are placed as values against the fieldnames in new dicts:

my_dict = {'App 1': 'App id1', 'App 2': 'App id2', 'App 3': 'App id3'}
with open('test.csv', 'w') as f:
    fieldnames = ['Application Name', 'Application ID']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    data = [dict(zip(fieldnames, [k, v])) for k, v in my_dict.items()]
    writer.writerows(data)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks! This almost solved my problem. However, I get an empty row after every item from my dictionary in the csv file. Is there a workaround for this? – Raj Aug 01 '17 at 22:40
  • 1
    @Raj Pretty common problem, see: https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row – Moses Koledoye Aug 01 '17 at 22:46
  • Thanks a lot @Moses – Raj Aug 01 '17 at 22:56
3

You can also do this without an import and fewer lines of code:

my_dict = {'App 1': 'App id1', 'App 2': 'App id2', 'App 3': 'App id3'}
with open('test.csv', 'w') as f:
    f.write('Application Name, Application ID\n')
    for key in my_dict.keys():
        f.write("%s,%s\n"%(key,my_dict[key]))
BHawk
  • 2,382
  • 1
  • 16
  • 24