通过Python字典循环

Hel*_*ely 1 python dictionary python-2.7

我正在尝试遍历字典并附加到字符串 - 这里是代码:

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
Run Code Online (Sandbox Code Playgroud)

这是打印'select * from maintable where age=23 and name=jame and time=next and' 我的问题是在结果的末尾有一个'和'.

如何在没有最后一个的情况下运行for循环?

任何帮助,将不胜感激.

Mar*_*ers 5

使用该str.join()方法将字符串与' and '分隔符连接在一起:

myquery = "select * from players where {}".format(
    ' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

但是,它看起来好像在构建SQL查询; 在这种情况下不要插值,请改用SQL参数:

myquery = "select * from players where {}".format(
    ' and '.join('{}=?'.format(k) for k in mylist))
Run Code Online (Sandbox Code Playgroud)

然后使用cursor.execute(myquery, mylist.values())将参数传递给数据库适配器.

检查数据库适配器使用的格式; 一些使用%s(C sprintf样式)和其他?用作占位符.