使用 Psycopg2 插入 Python 嵌套字典
Insert Python Nested Dictionary using Psycopg2
我正在尝试将嵌套字典结构插入 postgredb。我的词典如下:
dict = {'x': {'2022-02-09': 0.8},'y':{'2022-02-14': 0.9},'z':{'2022-01-14': 0.4}}
我想像这样插入 table:
a b c
x 2022-02-09 0.8
y 2022-02-14 0.9
z 2022-01-14 0.4
我的代码如下:
conn = pg.connect("dbname=foo user=foo_user")
cursor = conn.cursor()
for name , date in dict.items():
cursor.execute(
"""
INSERT INTO "sometable" ("a","b","c")
VALUES (%s,%s,%s)
""", (name, date.keys(),date.values())
)conn.commit()
cursor.close()
conn.close()
当我 运行 代码时,我得到 psycopg2.ProgrammingError: can't adapt type 'dict_values'
使用 pyscopg2 适配器将 dict 值导入 postgre 的解决方案可能是什么?
我明白你的方法,但你弄错了。当您获得 date.keys
时,您将获得 ['2022-02-09', '2022-02-14', '2022-01-14']
。但是你需要一个一个执行。
因此这是你应该的样子
for name , date_info in dict.items():
for date, value in date_info.items():
cursor.execute(
"""INSERT INTO "sometable" ("a","b","c")
VALUES (%s,%s,%s)""",
(name, date, value))conn.commit()
我正在尝试将嵌套字典结构插入 postgredb。我的词典如下:
dict = {'x': {'2022-02-09': 0.8},'y':{'2022-02-14': 0.9},'z':{'2022-01-14': 0.4}}
我想像这样插入 table:
a b c
x 2022-02-09 0.8
y 2022-02-14 0.9
z 2022-01-14 0.4
我的代码如下:
conn = pg.connect("dbname=foo user=foo_user")
cursor = conn.cursor()
for name , date in dict.items():
cursor.execute(
"""
INSERT INTO "sometable" ("a","b","c")
VALUES (%s,%s,%s)
""", (name, date.keys(),date.values())
)conn.commit()
cursor.close()
conn.close()
当我 运行 代码时,我得到 psycopg2.ProgrammingError: can't adapt type 'dict_values'
使用 pyscopg2 适配器将 dict 值导入 postgre 的解决方案可能是什么?
我明白你的方法,但你弄错了。当您获得 date.keys
时,您将获得 ['2022-02-09', '2022-02-14', '2022-01-14']
。但是你需要一个一个执行。
因此这是你应该的样子
for name , date_info in dict.items():
for date, value in date_info.items():
cursor.execute(
"""INSERT INTO "sometable" ("a","b","c")
VALUES (%s,%s,%s)""",
(name, date, value))conn.commit()