Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.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
Postgresql 将python字典键、值对提取为字符串或可编辑项';键1,键2,…';和[价值1,价值2,…]_Postgresql_Python 3.x_Dictionary_String Formatting - Fatal编程技术网

Postgresql 将python字典键、值对提取为字符串或可编辑项';键1,键2,…';和[价值1,价值2,…]

Postgresql 将python字典键、值对提取为字符串或可编辑项';键1,键2,…';和[价值1,价值2,…],postgresql,python-3.x,dictionary,string-formatting,Postgresql,Python 3.x,Dictionary,String Formatting,使用psycopg2和postgresql 9.3需要使用以下语法将行插入表中: cur.execute( 'INSERT INTO customer (name,address) VALUES ('Herman M', '1313 mockingbird lane')) 如果数据来自字典{'name':'Herman M','address':'1313 mockingbird lane'},是否有更好、更具python风格的方法从字典中按顺序提取键和值: fields,values

使用psycopg2和postgresql 9.3需要使用以下语法将行插入表中:

cur.execute(
'INSERT INTO customer (name,address) VALUES ('Herman M', '1313 mockingbird lane'))
如果数据来自字典{'name':'Herman M','address':'1313 mockingbird lane'},是否有更好、更具python风格的方法从字典中按顺序提取键和值:

    fields,values = '',[]
    for k,v in dictionary.items():
        fields = ','.join((fields,k))
        values.append((v))
为此,请执行以下操作:

    cur.execute(
    "INSERT INTO {} ({}) VALUES {}".format(
        tablename,fields[1:],tuple(values)))

这是可行的,但在观看了Raymond Hettinger关于将代码转换为漂亮的惯用python的演讲后,我很敏感地意识到这是一个丑陋的事实,我正在复制数据。有更好的方法吗?

使用
光标中的字典。执行
方法

insert_query = """
    insert into customer (name, address)
    values (%(name)s, %(address)s)
"""
insert_dict = {
    'name': 'Herman M',
    'address': '1313 mockingbird lane'
}

cursor.execute(insert_query, insert_dict)