python - 从包含列表的 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']')
我需要删除末尾的单引号和括号,以便我的查询可以正常运行。我怎样才能做到这一点?我很抱歉,我很新学习这个。
解决方案
在列表的情况下,您可以使用 Python 的join
方法,例如使用
', '.join(['Blue','Red','Green']) # returns 'Blue, Red, Green'
非常接近我们想要的!我们只需要稍微调整一下即可在每个字符串周围添加引号。为此:
'"' + '", "'.join(['Blue','Red','Green']) + '"' #returns '"Blue", "Red", "Green"'
此外,要检查元素x
是否为列表,您可以检查if isinstance(x, list):
.
推荐阅读
- c++ - 如何使用析构函数删除在类构造函数中分配的动态内存
- splunk - 如何使用 Multisearch 在两个搜索查询之间进行交叉验证和计数
- angular - Angular,如何在没有更改检测问题的情况下将值从 HTML 模板传递到组件
- firebase - Facebook 登录弹出窗口不会显示在我的 React Native Expo 应用程序上(使用 Firebase)
- python - 如何在django的博客文章中指定用户?
- javascript - 拖动一个矩形并附加到相应的组
- azure-ad-b2c - B2C 自定义策略中的“CreateRandomString”函数问题
- python - 如何获取python中字符串出现的计数?
- python - Jupyter 安装失败
- javascript - 当我的 React 和 Node 服务器不同(Firebase)时,我遇到 Passport 问题,但当它们相同时(Heroku)没有问题