Search code examples
pythonsqlfor-loopsqlalchemywhere-clause

SQL: Loop through items in dictionary


I have created a dictionary as follows:

dict = { 'NASDAQ': {'AMZN%', 'AAPL%', 'ABNB%'}, 'TSX': {'SHOP%', 'L%', 'RY%', 'XIF%'}}

I want to write a for loop within a query to fetch data from a table TICKER_TABLE with a column called TICKER which contains the dict values.

The query I am writing is part of a broader Python loop that looks like this:

for key in dict.keys():
    query = """SELECT * FROM "TICKER_TABLE"
               WHERE "TICKER" LIKE (FOR ITEM IN dict.VALUES)""""

Is there a way to do this?


Solution

  • If TICKER_TABLE and TICKER it's varable use f before string and {} to add varable. I'm not very advanced with sql, so I will use an extra for loop in python, although it can probably be done better but I don't know what u actually need:

     for key in dict:
       for value in dict[key]:
         query = f"SELECT * FROM {TICKER_TABLE}
                   WHERE {TICKER} LIKE {value}"
    

    Every iteretion of second for loop to AMZN%, AAPL%, SHOP% etc

    Maby something for this will be helpful for u.