Dynamically create excel files from nested dictionaries consisting of dataframes

101 Views Asked by At

I have a nested dictionary consisting of countries, and each country consisting of technologies and their values in a form of dataframes. Something like this:

dict_all_files: { 'Country1': {'technology1: dataframe, 'technology2: dataframe, 'technology3: dataframe},
                { 'Country2': {'technology1: dataframe, 'technology2: dataframe, 'technology3: dataframe},
                ...
                { 'Country20': {'technology1: dataframe, 'technology2: dataframe, 'technology3: dataframe},

I want to dynamically create excel files based on the names of each country and todays date. I have tried this:

today = datetime.today().strftime("%d-%m-%Y")

for country, techs in dict_all_files.items():
    for technology, dataframe in techs.items():
        with pd.ExcelWriter(f"my_path\my_excel_{country}_{today}.xlsx") as writer: 
                dataframe.to_excel(writer, sheet_name=technology)

This code returns the correct filenames, but each file only has one sheet, and that sheet has the name of the last technology in the dictionaries. How can I improve this so that each file has multiple sheets with the name of each technology and the corresponding data?

0

There are 0 best solutions below