嵌套字典到csv excel

时间:2017-05-11 08:28:38

标签: python excel csv dictionary

我尝试了很多不同的方法来获得excel中的以下结果,

              Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Breakfast     0      0       289       0        265    0         0
Lunch         832    0       0         0        0      0         0
Dinner        201    0       0         0        0      0         620

来自关注词典:

 my_dict = {"Monday":{"Breakfast": 0, "Lunch": 832, "Dinner": 201},
       "Tuesday":{"Breakfast": 0, "Lunch": 0, "Dinner": 0},
       "Wednesday":{"Breakfast": 289, "Lunch": 0, "Dinner": 0},
       "Thursday":{"Breakfast": 0, "Lunch": 0, "Dinner": 0},
       "Friday":{"Breakfast": 265, "Lunch": 0, "Dinner": 0},
       "Saturday":{"Breakfast": 0, "Lunch": 0, "Dinner": 0},
       "Sunday":{"Breakfast": 0, "Lunch": 0, "Dinner": 620}}

但我无法得到我想要的结果。我做的一个尝试不起作用就是这个:

import csv
import itertools

headings = (d.keys()[0] for d in my_dict)
entries = (sorted(my_dict[index][col].items()) for index, col in 
enumerate(headings))

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['items'] + headings)

    for cols in itertools.iziplogest(*entries, fillvalue=['<n/a>']*len(entries[0])):
         csv_output.writerow([cols[0][0]]+[col[1] for col in cols])

我是编程新手,对面向对象还不太熟悉,所以我想找到一个尽可能直截了当的答案。谢谢!

1 个答案:

答案 0 :(得分:1)

尝试使用pandas!

如果您还没有安装包,请安装包。

pip install pandas 

然后执行以下代码:

import pandas as pd
df = pd.DataFrame.from_dict(data=my_dict)
df=df[['Monday','Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday']]
df.to_csv('output.csv',index=False)

你应该得到如下csv:

Monday Tuesday Wednesday Thursday Friday Saturday Sunday Breakfast 0 0 289 0 265 0 0 Dinner 201 0 0 0 0 0 620 Lunch 832 0 0 0 0 0 0

就是这样,你应该根据需要拥有一个csv!