How can I create a list of dataframes and get them back by calling a key value


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()

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:


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:




How can I do this?

Asked By: datashout



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].

Answered By: Timeless
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.