Python – How to write a dictionary to csv with a list as its value and add a title to it

How to write a dictionary to csv with a list as its value and add a title to it… here is a solution to the problem.

How to write a dictionary to csv with a list as its value and add a title to it

I have a dictionary whose value is a list and

I want to write it to a csv file where the keys and all the items (values) in the list are in separate cells in the cvs file, this is how my dictionary 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 the first cell of the first row in excel to contain r1, and all items in the list are in a separate cell. Then I need to add a title 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

Edit:

Here’s 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 a key in one cell, a value in one cell (the whole list). No attempt has been made with header

Solution

The question is: –

The enumerate() function adds a counter to the iterable. Therefore, for each element in the cursor, a tuple is generated using (counter, element); The for loop binds it to row_number and row, respectively. This is a built-in generator function, see http://docs.python.org/2/library/functions.html#enumerate .

This 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 this helps.

Related Problems and Solutions