[Python] How to convert dictionary into SQL Query?

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I need to convert my python dictionary to sql query. Below is how my dictionary looks like

    dict_info = {
    "Tables": [
    "product",
    "sales"
    ],
    "Columns": {
    "product": [
    "prod_id",
    "prod_desc",
    ],
    "sales": [
    "prod_id",
    "prod_sales",
    "prod_qty"
    ]
    },
    "Filter": {
    "region_id": "1,2",
    "state_id": "4,7,9",
    "store_id": "14",
    }
    }


    I am trying to make two different queries since there are two tables information.(if it is 3 tables, then I have to make 3 different queries.

    What I need.

    Query1= " SELECT product.prod_id, product.prod_desc FROM product WHERE product.region_id in
    (1,2) AND product.state_id in (4,7,9) AND product.store_id in (14);

    Query2= " SELECT product.prod_id, product.prod_sales, product.prod_qty FROM product WHERE
    sales.region_id in (1,2) AND sales.state_id in (4,7,9) AND sales.store_id in (14);


    What I tried:

    import pandas as pd
    import numpy as np

    get_tables = dict_info.get("Tables", [])
    get_columns = dict_info.get("Columns", [])

    for i in tables:
    query = "SELECT " + ", ".join(columns) + ' FROM ' + i ";"


    Need help in how to put filter statements in the same query and creating dynamic queries for each of table selected.

    Continue reading...

Compartilhe esta Página