python - 循环遍历 Python 字典

标签 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' 我的问题是结果末尾有一个“和”。

如何在没有 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/

相关文章:

python - 单元格pyqt中的小部件对齐

python - 如何在python中按键对字典进行排序

dictionary - 使用范围时,GO 是否总是以相同的顺序迭代映射条目?

dictionary - F# 和元组输出

python - 管理多级菜单中的后退按钮 - Telegram Bot (Python)

python - Django 'likes' - ManyToManyField 与新模型

python - 当多个元素具有最高计数时,pandas describe() - top 如何工作?

python - BeautifulSoup4 藏在哪里?

Python lxml - 返回空列表

c# linq 将三个列表连接到嵌套字典