Writing a CSV horizontally

前端 未结 2 2066
逝去的感伤
逝去的感伤 2021-01-17 00:26

Say we are reading data from some source with multiple key-value pairs. Let\'s use the following list as an example:

[{\'key0\': \'key0_value0\', \'key1\': \         


        
2条回答
  •  醉酒成梦
    2021-01-17 00:52

    You'll have to first collect all your 'columns', then write. You can do that by converting everything to a list of lists, then use zip(*columns) to transpose the list of columns to a list of rows:

    columns = [['key_header'] + sorted(inputlist[0].keys())]  # first column
    
    for i, entry in enumerate(inputlist):
        columns.append([i] + [entry[k] for k in columns[0][1:]])
    
    with open(outputfilename, 'wb') as output:
        writer = csv.writer(output)
        writer.writerows(zip(*columns))
    

    Demo showing the row output:

    >>> from pprint import pprint
    >>> inputlist = [{'key0': 'key0_value0', 'key1': 'key1_value0'},
    ...  {'key0': 'key0_value1', 'key1': 'key1_value1'}]
    >>> columns = [['key_header'] + sorted(inputlist[0].keys())]  # first column
    >>> for i, entry in enumerate(inputlist):
    ...     columns.append([i] + [entry[k] for k in columns[0][1:]])
    ... 
    >>> pprint(zip(*columns))
    [('key_header', 0, 1),
     ('key0', 'key0_value0', 'key0_value1'),
     ('key1', 'key1_value0', 'key1_value1')]
    

提交回复
热议问题