Home > Enterprise >  Is it possible to create a dictionary where each value is a pandas dataframe?
Is it possible to create a dictionary where each value is a pandas dataframe?

Time:04-26

So, my question may not be that simple, but let's go:

let's say i have a function called create_a_dataframe() that i use to create dataframes and looks like this

def create_a_dataframe(place_where_data_comes_from)
   data = <gets data from place_where_data_comes_from>
   df = pd.DataFrame(data)
   return df

And i need to run this function 5 times, each time the function will return a dataframe that will be stored as a value in a dict:

my_5_values = [datasource1, datasource2, datasource3, datasource4, datasource5]
dict_with_dataframes = {}

for datasource in my_5_values:
   dict_with_dataframes[f"datasource name {datasource }"] = create_a_dataframe(datasource)

But when I try to show the first dataframe using

dict_with_dataframes['datasource name datasource1']

It returns a list with all the 5 keys and values. Am i doing something wrong?

CodePudding user response:

Do print(f"datasource name {datasource }"). It is not what you think it is.

datasource is just a dataframe value, not the string "datasource1". There is no good way to get a variable name. Instead, explicitly give names:

my_5_values = {"datasource1": datasource1,  ... }
dict_with_dataframes = {}

for name, datasource in my_5_values.items():
   dict_with_dataframes[f"datasource name {name}"] = create_a_dataframe(datasource)
  • Related