Skip to content Skip to sidebar Skip to footer

How To Write A List Of Tuple In Python With Header Mapping

I have to process python list of tuples where each tuple contains header name as below- I want all the tuple will be mapped to respectives header in that tuple. [[(u'Index', u'

Solution 1:

I found workaround at last-

Convert nested lists into dictionary and use dictwriter-

import csv
my_d = []
for i in datalist:
    my_d.append({x:y for x,y in i})

withopen("file.csv",'wb') as f:
   # Using dictionary keys as fieldnames for the CSV file header
   writer = csv.DictWriter(f, my_d[1].keys())
   writer.writeheader()
   for d in my_d:
      writer.writerow(d)

but it changes the order of the columns. If previous order needed i used header declaration and used in the dictwrites.

headers = [u'Index', u'Current', u'% Change', u'Open', u'High', u'Low', u'Prev. Close', u'Today', u'52w High', u'52w Low']

And used as below

writer = csv.DictWriter(f, headers)

That's solved my problem..

Post a Comment for "How To Write A List Of Tuple In Python With Header Mapping"