Write dictionary of lists to a CSV file

后端 未结 6 929
星月不相逢
星月不相逢 2020-12-01 08:01

I\'m struggling with writing a dictionary of lists to a .csv file.

This is how my dictionary looks like:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[k         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 08:17

    Roll your own without the csv module:

    d = {'key1' : [1,2,3],
         'key2' : [4,5,6],
         'key3' : [7,8,9]}
    
    column_sequence = sorted(d.keys())
    width = 6
    fmt = '{{:<{}}}'.format(width)
    fmt = fmt*len(column_sequence) + '\n'
    
    output_rows = zip(*[d[key] for key in column_sequence])
    
    with open('out.txt', 'wb') as f:
        f.write(fmt.format(*column_sequence))
        for row in output_rows:
            f.write(fmt.format(*row))
    

提交回复
热议问题