首页 > 解决方案 > 从包含列表的 Python 字典中替换 SQL“in”语句中的方括号和引号

问题描述

我正在尝试在我的 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']')

我需要删除末尾的单引号和括号,以便我的查询可以正常运行。我怎样才能做到这一点?我很抱歉,我很新学习这个。

标签: pythonsql

解决方案


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

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

非常接近我们想要的!我们只需要稍微调整一下即可在每个字符串周围添加引号。为此:

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

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


推荐阅读