Context
I am looking to export a dictionary which contains a list of dictionaries as the value of each key:value pair:
dict = {'key_1':
[{'key_a': foo_1, 'key_b': bar_1},
{'key_a': foo_2, 'key_b': bar_2}],
'key_2':
[{'key_c': foo_1, 'key_d': bar_1}],
{'key_c': foo_2, 'key_d': bar_2}]
...}
The desired output will be a .csv file which has the keys of the first dictionary (key_1, key_2, etc.), as the first header row, then the keys of the nested dictionaries (key_a, key_b, etc.), as a second header row which corresponds to its respective key.
An example of the desired output looks like this, where the list index column refers to data stored within the dictionary at each respective index within the list of dictionaries:
╔════════════╦═══════════════╤═══════════════╗
║ ║ key_1 │ key_2 ║
║ List Index ╠═══════╤═══════╪═══════╤═══════╣
║ ║ key_a │ key_b │ key_c │ key_d ║
╠════════════╬═══════╪═══════╪═══════╪═══════╣
║ 0 ║ foo_1 │ bar_1 │ foo_1 │ bar_1 ║
╟────────────╫───────┼───────┼───────┼───────╢
║ 1 ║ foo_2 │ bar_2 │ foo_2 │ bar_2 ║
╟────────────╫───────┼───────┼───────┼───────╢
║ 2 ║ foo_3 │ bar_3 │ foo_3 │ bar_3 ║
╚════════════╩═══════╧═══════╧═══════╧═══════╝
Platform: Raspberry Pi 3b+, Python 3.6
Code
Currently, I am looking into different options for doing this, so do not have any coherent code which comes near working. However, in order of preference, here are a few options which I am considering:
Use pandas to form an array which mirrors the nature of the desired table. Then write this to CSV directly.
Write to CSV from the dictionary data-structure described above.
import csv field_names = dict.keys() header2 = {'%s' %dict.keys() : dict[key_1][0].keys()} with open('project_data.csv', 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() # Write header row containing the top field names writer.writerow(header2) #Write row containing the second field names
As is evident, this code needs further development to make it work as desired.
Another method I have not considered?
The Question
What would be the best approach to write to a CSV in this format?