How to write a dict to a csv that have a list as its value and add a header for it

I have a Dict that its value is a list, and I want to write it to a csv file which the key and all the items in a list (value) be in a separate cell in cvs file, this is how my Dict looks like:

my_dict = {'r1':[1,0,0,1,1,0,1,0], 'r2' : [0,1,1,0,1,1,0,0]}

so I want my first cell in the first row in excel contains r1, and the all the items in a list in a separated cell respectively . and then I need to add a header like this (it can be a list like : l = ['R','t1','t2','t3','t4','t5','t6','t7','t8'] How the result in excel will look like

EDITTED:

This is the code I tried:

with open (outputFileName, 'a') as outFile:
    writer = csv.writer(outFile)
    for r , t in enumerate(my_dict.items()):
        writer.writerow([r, *t])

but the result is the key in one cell, the value(whole list) in one cell. Tried nothing for the header yet

1 answer

  • answered 2018-03-21 05:45 the.salman.a

    The problem was:-

    The enumerate() function adds a counter to an iterable. So for each element in cursor , a tuple is produced with (counter, element) ; the for loop binds that to row_number and row , respectively. It's a builtin generator function, see http://docs.python.org/2/library/functions.html#enumerate .

    Here is the modified code.

    import csv
    my_dict = {'r1':[1,0,0,1,1,0,1,0], 'r2' : [0,1,1,0,1,1,0,0]}
    outputFileName = 'test32.csv'
    with open (outputFileName, 'a+') as outFile:
        writer = csv.writer(outFile)
        writer.writerow(['R','t1','t2','t3','t4','t5','t6','t7','t8'])
        for r , t in my_dict.items():
            writer.writerow([r, *t])
    

    Output-

     R,t1,t2,t3,t4,t5,t6,t7,t8
     r1,1,0,0,1,1,0,1,0
     r2,0,1,1,0,1,1,0,0
    

    Hope it helps.