Python 2.7 Python字典映射到SQL查询字符串
我有一个python字典,它将列名从源表映射到目标表 字典:Python 2.7 Python字典映射到SQL查询字符串,python-2.7,dictionary,pymssql,Python 2.7,Dictionary,Pymssql,我有一个python字典,它将列名从源表映射到目标表 字典: tablemap_computer = { 'ComputerID' : 'computer_id', 'HostName' : 'host_name', 'Number' : 'number' } 我需要动态生成以下查询字符串,以便在字典中添加新的列名对时,它将正确更新 ComputerID=%(computer_id)s, HostName=%(host_name), Number=%(number)s
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,'
您可能想尝试使用联接和列表理解
query = ', '.join([key + '=%(' + value + ')s' for key, value in tablemap_computer.items()])
以您提供的词典为例,最终将得到以下字符串:
HostName=%(host_name)s, Number=%(number)s, ComputerID=%(computer_id)s