When creating a nested dictionary of dataframes, how can I name a dictionary based on a list name of the dataframe?

Peter Otten __peter__ at web.de
Sun Jun 7 04:38:47 EDT 2020


Aaron wrote:

> When creating a nested dictionary of dataframes, how can I name a
> dictionary based on a list name of the dataframe?
> 
> Given the following:
> 
> # START CODE
> import pandas as pd
> 
> cars = {'Brand': ['Honda Civic','Toyota Corolla'],
>         'Price': [22000,25000]
>         }
> df_cars = pd.DataFrame(cars, columns = ['Brand','Price'])
> 
> trucks = {'Brand': ['GMC Sierra','Ford F-150'],
>         'Price': [50000,48000]
>         }
> df_trucks = pd.DataFrame(trucks, columns = ['Brand','Price'])
> 
> list_of_dfs = [df_cars, df_trucks]
> 
> # Not exactly sure how this code should be:
> dict_of_dfs = {}
> for df in list_of_dfs:
>     dict_of_dfs[name_of_df] = {}  # Not sure here
>     dict_of_dfs[name_of_df]['results'] = df  # Not sure here
> # END CODE

In the general case you can't find the name of a value, so you may start 
with the names and look up the dataframes in the global namespace:

list_of_df_names = ["df_cars", "df_trucks"]
dict_of_dfs = {
   name: {"results": globals()[name]}
   for name in list_of_df_names
}

Personally I would probably reorganize your code a bit and avoid the df_... 
names:

import pandas as pd

vehicles = dict(
    cars={
        'Brand': ['Honda Civic','Toyota Corolla'],
        'Price': [22000,25000]
    },
    trucks={
        'Brand': ['GMC Sierra','Ford F-150'],
        'Price': [50000,48000]
    }
)

dict_of_dfs = {
    name: {"results": pd.DataFrame(val)}
    for name, val in vehicles.items()
}




More information about the Python-list mailing list