Write dictionary of lists to a CSV file

后端 未结 6 926
星月不相逢
星月不相逢 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:21

    Given

    dict = {}
    dict['key1']=[1,2,3]
    dict['key2']=[4,5,6]
    dict['key3']=[7,8,9]
    

    The following code:

    COL_WIDTH = 6
    FMT = "%%-%ds" % COL_WIDTH
    
    keys = sorted(dict.keys())
    
    with open('out.csv', 'w') as csv:
        # Write keys    
        csv.write(''.join([FMT % k for k in keys]) + '\n')
    
        # Assume all values of dict are equal
        for i in range(len(dict[keys[0]])):
            csv.write(''.join([FMT % dict[k][i] for k in keys]) + '\n')
    

    produces a csv that looks like:

    key1  key2  key3
    1     4     7
    2     5     8
    3     6     9
    

提交回复
热议问题