0

I know this a basic question but I am trying to call data from the database and define each of these dataframes as different variables.

This is what i have tried

lst=['A','B','C']
for i in range(len(lst)):
    globals()[lst[i]]=***SQL query to import dataframes***

This is what I am looking for:

print(A)
*** Some Dataframe ***

Any help would be appreciated

Shawn Jamal
  • 170
  • 8
  • You can use pandas to read the tables import pandas as pd pd.read_sql() : https://pandas.pydata.org/docs/reference/api/pandas.read_sql.html – Nohman May 25 '22 at 18:57
  • 1
    You *really* shouldn't be dynamically creating variables. Just use a `dict`. – juanpa.arrivillaga May 25 '22 at 18:58
  • Does this answer your question? [Using a string variable as a variable name](https://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name) – Ynjxsjmh May 25 '22 at 19:01
  • Sorry, this does not answer my question but I will keep working on it – Shawn Jamal May 25 '22 at 19:08

2 Answers2

0

IIUC you can cycle through a sql query with different variables like this:

lst=['A','B','C']
for i in lst:
     f"""
     SELECT * FROM TABLE WHERE COLUMN1 = '{i}'
     """
ArchAngelPwn
  • 2,891
  • 1
  • 4
  • 17
0

I would recommend using the enumerate function doing for loop through list. This makes it possible for you to unpack the index, and the value of the current element. Like so:

lst=['A','B','C']
for index, value in enumerate(lst):
    # Do some code here
    pass

This is the pythonic way of looping through lists when accessing the values. Hope this helps.

Flavio
  • 73
  • 7