-1

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' Broad Market Indices :')],
    [(u'Index', u'CNX NIFTY'), (u'Current', u'7,950.90'), (u'% Change', u'0.03'), (u'Open', u'7,992.05'), (u'High', u'8,008.25'), (u'Low', u'7,930.65'), (u'Prev. Close', u'7,948.90'), (u'Today', u''), (u'52w High', u'9,119.20'), (u'52w Low', u'7,539.50')],
    [(u'Index', u'CNX NIFTY JUNIOR'), (u'Current', u'19,752.40'), (u'% Change', u'0.73'), (u'Open', u'19,765.10'), (u'High', u'19,808.25'), (u'Low', u'19,629.50'), (u'Prev. Close', u'19,609.75'), (u'Today', u''), (u'52w High', u'21,730.80'), (u'52w Low', u'16,271.45')]]

Now to want to write this list into csv that looks like in MS Excel as below-

csv

Thanks in advance.

Learner
  • 5,192
  • 1
  • 24
  • 36
  • Can you post what you've tried here, it looks like you're simply asking for code – EdChum Oct 02 '15 at 20:18
  • Thanks,I tried some csv writer like http://stackoverflow.com/questions/15578331/save-list-of-ordered-tuples-as-csv but i cant not getting the idea how to do header mapping. – Learner Oct 02 '15 at 20:22

1 Answers1

0

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})

with open("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..

Learner
  • 5,192
  • 1
  • 24
  • 36