python - Writing a CSV horizontally -


say reading data source multiple key-value pairs. let's use following list example:

[{'key0': 'key0_value0', 'key1': 'key1_value0'},  {'key0': 'key0_value1', 'key1': 'key1_value1'}] 

reading first item list should result in csv looking this:

key_header | 0 --------------------------- key0       | key0_value_0 key1       | key1_value_0 

reading second item should result in following:

key_header | 0            | 1 ---------------------------------------- key0       | key0_value_0 | key0_value_1 key1       | key1_value_0 | key1_value_1 

this goes on horizontally until until. algorithm write beyond me, , not sure if the csv module work since appears assume data written row @ time.

you'll have first collect 'columns', then write. can converting list of lists, use zip(*columns) transpose list of columns list of rows:

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

demo showing row output:

>>> 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 >>> i, entry in enumerate(inputlist): ...     columns.append([i] + [entry[k] k in columns[0][1:]]) ...  >>> pprint(zip(*columns)) [('key_header', 0, 1),  ('key0', 'key0_value0', 'key0_value1'),  ('key1', 'key1_value0', 'key1_value1')] 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

c++ - End of file on pipe magic during open -