import csv


def lodict2csv(listofdicts, out, fnames=None, header=True):
    """
    Write a dictionary list with csv formatting to the stream out.

    :param fnames: when provided as a list, it is used as the column selection,
                   otherwise all keys occuring at least once are used.
    :param header: should the header be written
    """
    if fnames is None:
        fnames = set([])
        for dictionary in listofdicts:
            fnames.update(list(dictionary.keys()))
        fnames = sorted(fnames)
    csv_writer = csv.DictWriter(out,
                                fieldnames=fnames,
                                restval='NA',
                                extrasaction='ignore')
    if header:
        csv_writer.writeheader()
    csv_writer.writerows(listofdicts)
    return len(listofdicts)