简体   繁体   中英

Write list of dicts to csv with values in separate columns

I'm having a hard time understanding how to write a list of dicts to csv in which all of my values are in separate columns. Questions similar to this here on SO have not helped me understand. I've been using the DictWriter but can't figure out how to feed the dict.values() in without an error 'field x not in fieldnames'.

.....

dicts = [
  {'sku': 'xxxx1', 'model': '1234-56K', 'price': '$xxx.xx', 'name': 'item_name_here', 'stock': 'True'},
  {'sku': 'xxxx2', 'model': '1234-56K', 'price': '$xxx.xx', 'name': 'item_name_here', 'stock': 'False'}
]

csv_file = open('file.csv','wb')
fieldnames = ('name', 'price', 'stock', 'model', 'sku')
csvwriter = csv.DictWriter(csv_file, fieldnames, extrasaction='raise', dialect='excel')
csvwriter.writeheader()
csvwriter.writerows(dicts)
return csv_file

.....

This returns my values in a single column, but when I iterate over the values of the dicts in the list it simply splits all values (as string) into 's,t,r,i,n,g,' still placing them into the first column.

From the docs for csv.DictWriter() :

If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise' a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored.

If this is the error you are getting, try:
csv.DictWriter(csv_file, fieldnames, extrasaction='ignore', dialect='excel')

hey i wrote this for Python 2.7

This function takes a list of dictionaries and outputs a csv. It also include options to set the order of the field in fieldNames, defaultFieldValues, sortField, and option to remove duplicates

https://gist.github.com/brendancol/6816393

def write_csv(outputRowDictionaries, outputFile, fieldNames=None, defaultFieldValue='', removeDuplicates=False, sortField=None):
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM