我想創建一個字典列表並導出到一個csv文件。這些字典長短不一 - 基本上我想這樣做如下:從不同大小的字典創建數據結構python3.x
a = {'name': 'Alison', 'food1': 'bananas', 'food2': 'apples', 'food3': 'dates'}
b = {'name': 'Ken', 'food1': 'noodles', 'food2': 'rice'}
c = {'name': 'Max', 'food1': 'jello', 'food2': 'yogurt', 'food3': 'bananas', 'food4': 'milk}
輸出CSV
name | food1 | food2 | food3 | food4
------------------------------------------------------------------------
Alison | bananas | apples | dates | ' '
Ken | noodles | rice | ' ' | ' '
Max | jello | yogurt | bananas | milk
# list of dictionaries
data = [a, b, c]
目前,我有一些代碼,以便能夠從詞典列表創建數據結構只要該列表中的每個字典具有相同數量的密鑰即可。
keys = data[0].keys()
with open('profiles.csv', 'w', newline = '') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(data)
有人有辦法將長度不同的字典列表合併到上面顯示的csv中嗎?
考慮使用'defaultdict'或'pandas'。 –