Created
October 3, 2013 20:14
-
-
Save brendancol/6816393 to your computer and use it in GitHub Desktop.
python: list of dictionaries to csv example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def write_csv(outputRowDictionaries, outputFile, fieldNames=None, defaultFieldValue='', removeDuplicates=False, sortField=None): | |
dictionaryList = [] | |
if removeDuplicates: | |
for row in outputRowDictionaries: | |
if row not in dictionaryList: | |
dictionaryList.append(row) | |
else: | |
dictionaryList = outputRowDictionaries | |
if sortField: | |
dictionaryList = sorted(dictionaryList, key=lambda k: k[sortField]) | |
with open(outputFile, 'wb') as output_csv: | |
if not fieldNames: | |
fieldNames = [f.encode('utf-8') for f in dictionaryList[0].keys()] | |
fieldNames.sort() | |
csvWriter = csv.DictWriter(output_csv, delimiter=',', fieldnames=fieldNames) | |
headers = {} | |
for field_name in fieldNames: | |
headers[field_name] = field_name | |
csvWriter.writerow(headers) | |
for m in dictionaryList: | |
row = {} | |
for k, v in m.items(): | |
if type(v) in [types.StringType, types.UnicodeType]: | |
row[k.encode('utf-8')] = v.encode('utf-8') | |
else: | |
row[k] = v | |
for f in fieldNames: | |
if not row.get(f): | |
row[f] = defaultFieldValue | |
csvWriter.writerow(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment