我正在尝试遍历字典并附加到字符串 - 这是代码:
mylist= {'name':'james', 'age': '23', 'time': 'next'}
myquery = "select * from players where"
for k, v in mylist.items():
myquery += "%s=%s and" % (k, v),
print myquery
这是打印 'select * from maintable where age=23 and name=jame and time=next and'
我的问题是结果末尾有一个“和”。
如何在没有 last and 的情况下运行 for 循环?
如有任何帮助,我们将不胜感激。
最佳答案
使用 str.join()
method使用 ' 和 '
分隔符将字符串连接在一起:
myquery = "select * from players where {}".format(
' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))
演示:
>>> mylist= {'name':'james', 'age': '23', 'time': 'next'}
>>> "select * from players where {}".format(
... ' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))
'select * from players where age=23 and name=james and time=next'
但是,看起来您正在构建 SQL 查询;在这种情况下不要插入值,而是使用 SQL 参数:
myquery = "select * from players where {}".format(
' and '.join('{}=?'.format(k) for k in mylist))
然后使用 cursor.execute(myquery, mylist.values())
将参数传递给数据库适配器。
检查你的数据库适配器使用什么格式;一些使用 %s
(C sprintf 风格),另一些使用 ?
作为占位符。
关于python - 循环遍历 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18531483/