When creating a nested dictionary of dataframes, how can I name a dictionary based on a list name of the dataframe?
Aaron
aaron.christensen at gmail.com
Sat Jun 6 17:08:02 EDT 2020
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
I am trying to use a for loop that performs the following:
# START CODE
dict_of_dfs['df_cars'] = {}
dict_of_dfs['df_cars']['results'] = df_cars
dict_of_dfs['df_trucks'] = {}
dict_of_dfs['df_trucks']['results'] = df_trucks
# END CODE
The above code should produce the following desired output:
{
'df_cars': {
'results':
Brand Price
0 Honda Civic 22000
1 Toyota Corolla 25000},
'df_trucks': {
'results':
Brand Price
0 GMC Sierra 50000
1 Ford F-150 48000}
}
I've read multiple threads, used the module varname, and tried using
enumerate() but have been unsuccessful.
Thank you!
More information about the Python-list
mailing list