Python: convert list of dicts to csv

The following function converts a list of dicts to a unicode string that can be piped into a csv file. All cells are quoted. If the dict contains lists, then these are written as a list of items within a cell, with each item separated by a comma and single space.

import itertools

def dict2csv(d):
    out = u''
    keys = []
    for key, value in d[0].iteritems():
        keys.append(key)
        out += u'"'+key+u'",'
    out += u'\n'
    for row in d:
        for key in keys:
            if isinstance(row[key],unicode):
                out += u'"'+row[key]+u'",'
            elif isinstance(row[key],list):
                out += u'"'
                for a in row[key]:
                    out += a+u', '
                out += u'",'
        out += u'\n'
    return out

Usage example:

with io.open('output.csv', 'w', encoding='utf-8') as file:
    file.write(dict2csv(mydict))
Creative Commons License
This work by pete is licensed under a Creative Commons Attribution 4.0 International