Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何修复此dict和postgreSQL_Python 3.x_Postgresql 9.3 - Fatal编程技术网

Python 3.x 如何修复此dict和postgreSQL

Python 3.x 如何修复此dict和postgreSQL,python-3.x,postgresql-9.3,Python 3.x,Postgresql 9.3,我只想更新我的键,我的dict中的值 这是用于使用python dict更新PostgreSQL的 data ={ 'created_by':'obama', 'last_updated_by':'nandu', 'effective_from':'2019-12-30', 'effective_to':'2017-12-30' } lst= list() lst1 = list() for key,value

我只想更新我的键,我的dict中的值

这是用于使用python dict更新PostgreSQL的

data ={

        'created_by':'obama',
        'last_updated_by':'nandu',
        'effective_from':'2019-12-30',
        'effective_to':'2017-12-30'
        }

lst= list()
lst1 = list()

for key,value in data.items():    
    lst.append(key)
    lst1.append(value)

keys = tuple(lst)
values = tuple(lst1)

update = "UPDATE table_name SET %s = %s where name = 'kumar'"
cur.execute(update,(keys,values))
我想将键设置为字段名,将值设置为值 但是我得到的字段名(键)是字符串
所以我得到了语法错误

您不能将元组用于SET。最好是在dict上循环,每次设置一个键:

data ={'created_by':'obama',
       'last_updated_by':'nandu',
       'effective_from':'2019-12-30',
       'effective_to':'2017-12-30',
}

for key, value in data.items():    
    update = "UPDATE table_name SET %s = %s where name = 'kumar'"
    cur.execute(update,(key, value))
或者按照建议使用f字符串

data ={'created_by':'obama',
       'last_updated_by':'nandu',
       'effective_from':'2019-12-30',
       'effective_to':'2017-12-30',
}

arguments = ','.join([f'{key}=\'{val}\'' for key, val in data.items()])

update = f"UPDATE table_name SET {arguments} where name = 'kumar'"
cur.execute(update)

您不需要
lst
lst1
键和
值的临时变量。您可以使用
assignments=['%s=%s%%(key,value)作为数据中的key,value.items()]
set\u子句='set%s'%assignments
update=“update table\u name%s其中name='kumar'%set\u子句