词典词典 Excel

Dictionary of Dictionaries to Excel

我有一本字典的字典 (Di_1):

Di_1 = {1 : {101 : ['cat', 'mouse'],
             102 : ['dog'],
             103 : []},
        2 : {101 : ['cat', 'mouse', 'dog'],
             102 : ['dog', 'cat'],
             103 : ['mouse']},
        3 : {101 : ['cat', 'mouse', 'dog', 'lion'],
             102 : ['dog', 'cat'],
             103 : ['mouse', 'dragon']}}

我想将其导出到 Excel (test_1.xlsx)。 我在 Pandas:

试过了
import pandas as pd
writer = pd.ExcelWriter('test_1.xlsx', engine='openpyxl') 
for A in [1,2,3]:
    df_A = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in Di_1[A].items() ])).T
    df_A.to_excel(writer, sheet_name=str(A))

此代码 运行 但它没有将任何内容导出到 excel。请问如何导出?

此处遗漏writer.save():

writer = pd.ExcelWriter('test_1.xlsx', engine='openpyxl') 
for A in [1,2,3]:
    df_A = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in Di_1[A].items() ])).T
    df_A.to_excel(writer, sheet_name=str(A))
  
writer.save()

解决方案应该用 DataFrame.from_dict 来简化:

writer = pd.ExcelWriter('test_1.xlsx', engine='openpyxl') 
for A in [1,2,3]:
    df_A = pd.DataFrame.from_dict(Di_1[A], orient='index')
    df_A.to_excel(writer, sheet_name=str(A))
  
writer.save()