Python Dictionary to CSV

后端 未结 6 773
情深已故
情深已故 2020-11-27 16:09

I have written code to read a CSV into a python dictionary, which works fine. I\'m trying to get the dictionary back to a CSV. I have written the following:

         


        
6条回答
  •  一生所求
    2020-11-27 16:47

    The default writer expects a list, which is why it won't work for you. To use the dictwriter, just change your listwriter = line to this:

    with open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb') as outfile:
        listWriter = csv.DictWriter(
           outfile,
           fieldnames=itemDict[itemDict.keys()[0]].keys(),
           delimiter=',',
           quotechar='|',
           quoting=csv.QUOTE_MINIMAL
        )
    

    Or, you can just set fieldnames to be fieldnames=['arbitrary','list','of','keys'] if you know what the fields are supposed to be.

提交回复
热议问题