1

I have d1, d2, ..., dn dictionaries of the same len and need to dump them into the columns of a new csv file.

I would like the file to have its headers and to look pretty much like this:

        |STAGE 1      | |STAGE 2               | |TOTAL                |
SIM     d1  d2  d3  d4  d5  d6  d7  d8  d9  d10  d11  d12  d13  d14  d15    
event 1
event 2
event 3
event 4
event n

Each d column should have the values of the corresponding dictionary aligned below, and a tab should work well in order to separate each column.

I know I could create a csv file like this:

import csv

my_d = {"STAGE 1": 1, "STAGE 2": 2, "TOTAL": 3}

with open('mycsvfile.csv', 'wb') as csvfile:  
    w = csv.DictWriter(csvfile, my_d.keys())
    w.writeheader()
    w.writerow(my_d)

but I can't seem to find my way out and also I failed to figure out how to make headers like d1 appear as sub-headers. How could this be done in Python?

FaCoffee
  • 7,609
  • 28
  • 99
  • 174

1 Answers1

1

If you transpose the lists you will be able to write to the csv similar to your example.

h1 = ['a','b','c','d','e']
d1 = [1, 2, 3, 4, 5]
d2 = [1, 2, 3, 4, 5]
d3 = [1, 2, 3, 4, 5]

transpose =  [h1, d1, d2, d3]

print(transpose)
print(list(map(list, zip(*transpose)))) 

outputs:

>>> 
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
[['a', 1, 1, 1], ['b', 2, 2, 2], ['c', 3, 3, 3], ['d', 4, 4, 4], ['e', 5, 5, 5]]
>>> 

This assumes your using Python 3, if you're using python 2 print(map(list, zip(*l))) instead

Woodsy
  • 3,177
  • 2
  • 26
  • 50
  • I have a number of `dicts` rather than `lists`. Are they transposable as well? – FaCoffee Nov 04 '15 at 16:12
  • if not, you can convert the dictionaries to lists: http://stackoverflow.com/questions/1679384/converting-python-dictionary-to-list – Woodsy Nov 04 '15 at 16:49