Q:

The best way to write a dictionary to a CSV file when the values are 2d lists?

I have the following dictionary
dict = {5: [ [a00, a01, ..., a0n], [a10, a11, ..., a1n], ... ],
        6: [ [b00, b01, ..., b0n], [b10, b11, ..., b1n], ... ],
        7: [ [c00, c01, ..., c0n], [c10, c11, ..., c1n], ... ],               
        8: etcetera }

All the 2d lists have the same amount of columns, but different amount of rows.
What is the best way to write this to a csv file. Currently I use
w = csv.writer(open("python_output.csv", "w"))
for key, val in dict.items():
    w.writerow([key, val])

But this doesn't work, because the entire 2d list gets put in one cell in the CSV file. 

A:

You can use writerows method available for csv.writer
import csv
dict1 = {5: [['a00', 'a01', 'a0n'], ['a10', 'a11', 'a1n'], ['a20', 'a21', 'a2n']], 6: [['b00', 'b01', 'b0n'], ['b10', 'b11', 'b1n'], ['b20', 'b21', 'b2n']], 7: [['c00', 'c01', 'c0n'], ['c10', 'c11', 'c1n'], ['c20', 'c21', 'c2n']], 8: [['d00', 'd01', 'd0n'], ['d10', 'd11', 'd1n'], ['d20', 'd21', 'd2n']]}
rows = [[k]+l for k,v in dict1.items() for l in v]
with open('tmp.txt', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(rows)

Output
5,a00,a01,a0n
5,a10,a11,a1n
5,a20,a21,a2n
6,b00,b01,b0n
6,b10,b11,b1n
6,b20,b21,b2n
7,c00,c01,c0n
7,c10,c11,c1n
7,c20,c21,c2n
8,d00,d01,d0n
8,d10,d11,d1n
8,d20,d21,d2n

