簡體   English   中英

替換包含列表的 Python 字典中 SQL“in”語句中的方括號和引號

[英]Replacing square brackets and quotations in SQL "in" statement from Python dictionary containing a list

我正在嘗試在我的 Python 腳本中運行一些 SQL。 我想在 SQL "in" 語句中使用的過濾器之一來自 Python 字典。 字典中的一項可以具有字典中列表中的多個值。 我希望能夠通過 SQL "in" 語句傳遞字典,而無需添加額外的括號或方括號。

我擁有的:

code: 1      ###(or 2, or 3, or 4)
dictionary = {'1': 'Blue', '2': 'Red', '3': 'Green', '4': ['Blue','Red','Green']}

print("""select * from table a
where and a.color in (""" "{}".format(dictionary[code])+ """) ;""")

問題:對於字典中只有一個鍵對(1、2 和 3)的項目,插入到查詢中可以正常工作。 對於這些,結果是:

select * from table a where a.color in ('Blue')
select * from table a where a.color in ('Red')       
select * from table a where a.color in ('Green')

當我嘗試引用字典中的列表時,我得到一個包含方括號和單引號的字符串,例如:

select * from table a where a.color in ('['Blue', 'Red', 'Green']')

我需要刪除末尾的單引號和括號,以便我的查詢可以正常運行。 我怎樣才能做到這一點? 我很抱歉,我是新學的。

在列表的情況下,您可以使用 Python 的join方法,例如使用

', '.join(['Blue','Red','Green']) # returns 'Blue, Red, Green'

非常接近我們想要的! 我們只需要稍微調整一下以在每個字符串周圍添加引號。 這樣做:

'"' + '", "'.join(['Blue','Red','Green']) + '"'  #returns '"Blue", "Red", "Green"'

此外,要檢查元素x是否是列表,您可以檢查if isinstance(x, list):

正如@Anis R. 提到的; 您需要加入列表,但前提是它是列表。

這是一個完整的工作示例:)

#code = 2     ###(or 2, or 3, or 4)
dictionary = {'1': 'Blue', '2': 'Red', '3': 'Green', '4': ['Blue','Red','Green']}

def get_sql(code):
    lbl = ''

    # print(type(dictionary[str(code)]))

    if type(dictionary[str(code)]) == str:
        lbl = dictionary[str(code)]
    else:
        lbl = "', '".join(dictionary[str(code)])

    return ("select * from table a where and a.color in ('" + lbl + "') ;")

print(get_sql(2))
print(get_sql(4))

生產

select * from table a where and a.color in ('Red') ;
select * from table a where and a.color in ('Blue', 'Red', 'Green') ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM