How to write a list of tuple in python with header mapping

左心房为你撑大大i 提交于 2019-12-13 08:58:55

问题


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-

Thanks in advance.


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

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..



来源:https://stackoverflow.com/questions/32915172/how-to-write-a-list-of-tuple-in-python-with-header-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!