Write dictionary to a CSV, where keys are row numbers and values are a list.
970402
def writeFromDict(dataDict, headers, csvFile):
  
  with open(csvFile, "wb") as f:
    writer = csv.writer(f, delimiter=",")
    writer.writerow(headers)
    for row in sorted(dataDict.keys()):
      writer.writerow(dataDict[row])
992866
private static byte[] writeCsv(String[] columnHeaders, String[][] rows) throws IOException {
    try (ByteArrayOutputStream csvStream = new ByteArrayOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(csvStream, Charset.forName("UTF-8"))) {
      CSVWriter csvWriter = new CSVWriter(streamWriter, ',');

      csvWriter.writeNext(columnHeaders);
      
      for (String[] row : rows) {
        csvWriter.writeNext(row);
      }

      csvWriter.close();
      
      return csvStream.toByteArray();
    }
  }
845662
def csv_to_dicts(file, header=None):
    """"""
    with open(file) as csvfile:
        return [row for row in csv.DictReader(csvfile, fieldnames=header)]
886057
def rows_to_dicts(self, serialize_cell=None):
    """"""
    if serialize_cell is None:
      serialize_cell = self.get_cell_value
    # keys = [serialize_cell(cell) for cell in self.rows[0]]
    keys = self.headers(serialize_cell)
    for row in self.rows[1:]:
      yield dict(zip(keys, [serialize_cell(cell) for cell in row]))
267554
def csv(self):
        
        lines = self._parsecsv(self.raw)

        # set keys from header line (first line)
        keys = next(lines)

        for line in lines:
            yield dict(zip(keys, line))
485699
def write_data_csv(fname, frames, preproc):
   """"""
   fdata = open(fname, "w")
   dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames)
   data,result = zip(*dr)
   for entry in data:
      fdata.write(','.join(entry)+'\r\n')
   print("All finished, %d slices in total" % len(data))
   fdata.close()
   result = np.ravel(result)
   return result
4810
def encode_list(key, list_):
    # type: (str, Iterable) -> Dict[str, str]
    
    if not list_:
        return {}
    return {key: " ".join(str(i) for i in list_)}
1339424
def _dict_factory(cursor, row):
        ''' 
        '''
        d = {}
        for idx, col in enumerate(cursor.description):
            if col[0] == 'rowid':
                d['_id'] = row[idx]
            else:
                d[col[0]] = row[idx]
        return d
785930
def csv_dict(d):
    
    if len(d) == 0:
        return "{}"
    return "{" + ', '.join(["'{}': {}".format(k, quotable(v))
                            for k, v in d.items()]) + "}"
901132
def make_csv(data):
    
    # Convert sub-dicts to news cols
    for entry in data:
        rval = entry
        if isinstance(data, dict):
            rval = data[entry]
        todel = []
        toadd = {}
        for key, val in rval.items():
            if isinstance(val, dict):
                for key2, val2 in val.items():
                    toadd[str(key) + "[" + str(key2) + "]"] = val2
                todel.append(key)
        for k in todel:
            del rval[k]
        for k, v in toadd.items():
            rval[k] = v

    # Convert everything to CSV
    columns = set()
    output = [[]]
    if isinstance(data, dict):
        output[0].append("id")
        for entry in data:
            for col in data[entry]:
                columns.add(col)
    else:
        for entry in data:
            for col in entry:
                columns.add(col)

    columns = sorted(columns)

    for col in columns:
        output[0].append(col)

    if isinstance(data, dict):
        for entry in data:
            new_output = [str(entry)]
            for col in columns:
                new_output.append(str(data[entry][col]) if col in data[entry] else "")
            output.append(new_output)
    else:
        for entry in data:
            new_output = []
            for col in columns:
                new_output.append(str(entry[col]) if col in entry else "")
            output.append(new_output)

    csv_string = io.StringIO()
    csv_writer = UnicodeWriter(csv_string)
    for row in output:
        csv_writer.writerow(row)
    csv_string.seek(0)
    web.header('Content-Type', 'text/csv; charset=utf-8')
    web.header('Content-disposition', 'attachment; filename=export.csv')
    return csv_string.read()
775855
def write_to_csv(self, filename):
        '''
        
        '''
        fid = open(filename, 'wt')
        # Create header list
        header_info = ['Longitude', 'Latitude', 'Depth', 'Observed Count',
                       'Smoothed Rate', 'b-value']
        writer = csv.DictWriter(fid, fieldnames=header_info)
        headers = dict((name0, name0) for name0 in header_info)
        # Write to file
        writer.writerow(headers)
        for row in self.data:
            # institute crude compression by omitting points with no seismicity
            # and taking advantage of the %g format
            if row[4] == 0:
                continue
            row_dict = {'Longitude': '%g' % row[0],
                        'Latitude': '%g' % row[1],
                        'Depth': '%g' % row[2],
                        'Observed Count': '%d' % row[3],
                        'Smoothed Rate': '%.6g' % row[4],
                        'b-value': '%g' % self.bval}
            writer.writerow(row_dict)
        fid.close()
673931
def _write_csv(f, table_):
    
    fieldnames = table_[0].keys()
    set_fieldname = set(table_[0].keys())
    # go through all the fields and find all the field names
    for row in table_:
        set_fieldname.update(set(row.keys()))

    # append the additonal fields sorted onto the end
    additional_fields = sorted(set_fieldname - set(table_[0].keys()))
    fieldnames += additional_fields

    writer = unicodecsv.DictWriter(f, fieldnames, encoding='utf-8')
    writer.writeheader()

    # Change lists into comma-separated strings.
    for dict_ in table_:
        for key, value in dict_.items():
            if type(value) in (list, tuple):
                dict_[key] = ', '.join([unicode(v) for v in value])

    writer.writerows(table_)
908629
def write_text_rows(writer, rows):
    ''''''
    for row in rows:
        try:
            writer.writerow(row)
        except UnicodeEncodeError:
            # Python 2 csv does badly with unicode outside of ASCII
            new_row = []
            for item in row:
                if isinstance(item, text_type):
                    new_row.append(item.encode('utf-8'))
                else:
                    new_row.append(item)
            writer.writerow(new_row)
420776
def _tabulate(rows, headers, spacing=5):
    """"""
    if len(rows) == 0:
        return "None\n"
    assert len(rows[0]) == len(headers)
    count = len(rows[0])
    widths = [0 for _ in range(count)]
    rows = [headers] + rows

    for row in rows:
        for index, field in enumerate(row):
            if len(str(field)) > widths[index]:
                widths[index] = len(str(field))

    output = ""
    for row in rows:
        for index, field in enumerate(row):
            field = str(field)
            output += field + (widths[index] - len(field) + spacing) * " "
        output += "\n"
    return output
698436
def to_python(self):
        """"""
        # Adding rows
        items = []
        for row in self.rows:
            formatted_row = [_format_python_value(v) for v in row]
            items.append(dict(zip(self.columns, formatted_row)))
        return items
1157765
function csv(arg) {
  return ( _.isArray(arg) ? arg :
           _.isObject(arg) ? _.values(arg) :
           [arg]).join(', ');
}
483039
def make_csv(self):
        
        import csv
        try:
            from StringIO import StringIO  # Python 2.7
        except ImportError:
            from io import StringIO

        out = StringIO()
        writer = csv.writer(out, delimiter='|', lineterminator='\n', quoting=csv.QUOTE_MINIMAL)

        if self.function == 'total':
            writer.writerows(self.results)                

        elif self.function == 'top':
            rows = [['Value', self.headers.strip('"')]]
            if self.results[0] is not None:
                for res in self.results:
                    if res is not None:
                        rows.append(tuple([res[0], ','.join(res[1])]))
                writer.writerows(rows)
                
        elif self.function == 'table':
            rows = [[header.strip('"') for header in re.split('\s*,\s*', self.headers)]]

            for res in sorted(self.results, key=lambda x: x[0]):
                row = list(res[:-1])
                lastcol = get_fmt_results(res[-1], limit=10)
                if lastcol[-1][0] == '[' and lastcol[-1][-1] == ']':
                    row.append(u'{0} {1}'.format(u', '.join(lastcol[:-1]), lastcol[-1]))
                else:
                    row.append(u', '.join(lastcol))
                rows.append(row)
            writer.writerows(rows)

        self.csv = out.getvalue()