Home > Software engineering >  Pandas read_sql_query with comprehension in params
Pandas read_sql_query with comprehension in params

Time:12-13

I'm trying to do a SQL query with Pandas. I have 3 params, initial_date, final_date and trader, where trader is a list. (. My query looks like this :

Select * from
tables.table T
where trader in (:trader)
and date >= :initial_date and data <= :final_date

In my params, i'm trying to do some like this:

params = {
    'initial_date': initial_date.strftime('%Y-%m-%d'),
    'final_date': final_date.strftime('%Y-%m-%d'),
    f":trader{counter}": traders for counter,traders in enumerate(trader)}

but i have been receiving this in my IDE (Visual Studio Code) :

Comprehension cannot be used with other dictionary entries Pylance

Can someone help me to fix this?

CodePudding user response:

You can have only one key-value pair in a dict comprehension.

Try

params = {'initial_date': initial_date.strftime('%Y-%m-%d'),
          'final_date': final_date.strftime('%Y-%m-%d')}

params.update({f":trader{counter}": traders for counter,traders in enumerate(trader)})

CodePudding user response:

There's only one trader value to substitute. Assuming your database adapter can handle lists, you should just need

params = {
    'initial_date': initial_date,
    'final_date': final_date,
    "trader": list(trader)
}

You shouldn't need to convert the dates to strings. Most database connectors can handle date types.

  • Related