Python 字典映射到 SQL 查询字符串

Python dictionary map to SQL query string

我有一个 python 字典,可以将列名称从源 table 映射到目标 table。

词典:

tablemap_computer = {
    'ComputerID' : 'computer_id',
    'HostName' : 'host_name',
    'Number' : 'number'
}

我需要动态生成以下查询字符串,以便在将新的列名称对添加到字典时正确更新。

ComputerID=%(computer_id)s, HostName=%(host_name), Number=%(number)s

执行此操作的好方法是什么?

我有一个开始,但它很乱,最后一个元素的末尾有一个额外的逗号。

queryStrInsert = ''
for tm_key, tm_val in tablemap_computer.items():
    queryStrInsert += tm_key+'=%('+tm_val+')s,'

您可能想尝试使用 join 和列表理解。

query = ', '.join([key + '=%(' + value + ')s' for key, value in tablemap_computer.items()])

使用您提供的字典作为示例,最终会得到以下字符串:

HostName=%(host_name)s, Number=%(number)s, ComputerID=%(computer_id)s