I am running a for loop like this:
tracks = [1010, 2020]
df_list = []
for i in tracks:
query = ''' quer_here '''
df = pd.read_sql(query, con=con)
to_dict = df.to_dict()
df_list.append(to_dict)
So i am running a query, reading it as pandas dataframe then the dataframe to dict and append this dict to a list.
From here I can get the dataframe back calling, for example:
pd.DataFrame(df_list[0])
What I want to do from here is to append every dict with a key that is the i
value so I can get the dataframe back calling:
pd.DataFrame(df_list[1010])
or
pd.DataFrame(df_list[2020])
How can I do this?
CodePudding user response:
Why are you calling pandas.DataFrame.to_dict
to convert the dataframe created by each SQL query to a dictionnary and after that, using pandas.DataFrame
constructor to do a rollback ?
IMO, you can simply use :
tracks = [1010, 2020]
df_dict = {}
for i in tracks:
query = ''' quer_here '''
df_dict[i] = pd.read_sql(query, con=con)
NB: This will create a dictionnary with tracks as keys and dataframes as values. You can access each dataframe by using key-based indexing : df_dict[1010], df_dict[2020]
.