Create a gist now

Instantly share code, notes, and snippets.

@stennie / Secret
Created Sep 7, 2012

What would you like to do?
Convert results of a aggregate framework to CSV (
#!/usr/bin/env python
import csv
def quoteStrings(strArr):
return ["'%s'"%k for k in strArr]
result = [
{'_id': 'Rob', 'x': [12], 'y': [2], 'z': []},
{'_id': 'George', 'x': [5], 'y': [3], 'z': [9]}
# open file and create csv writer
f = open('out.csv', 'w')
writer = csv.writer(f)
# flatten sub-arrays to double-quoted comma-separated strings, e.g. [1, 2, 3] ==> "1, 2, 3"
for i, row in enumerate(result):
for key in row:
if isinstance(row[key], list):
result[i][key] = ','.join([str(x) for x in row[key]])
# write keys to csv
keys = [k for k in result[0].keys() if k!='_id']
writer.writerow(quoteStrings(['Name'] + keys))
for row in result:
writer.writerow(quoteStrings([row[k] for k in ['_id'] + keys]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment