通过Python字典循环

时间:2013-08-30 11:10:42

标签: python python-2.7 dictionary

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

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' 我的问题是结果有一个'和'。

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

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:5)

使用str.join() method将字符串与' and '分隔符连接起来:

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样式),有些人使用?作为占位符。

答案 1 :(得分:2)

在for循环结束时添加此语句,该语句将从查询语句中删除和。

if myquery.endswith('and'):
   myquery = myquery[:-3]